From 61ad868ed3a8f9e08d0e00de3e97ade6476f4190 Mon Sep 17 00:00:00 2001 From: Jamie Grant Date: Wed, 9 Sep 2026 09:13:30 +0100 Subject: [PATCH] TorqX consolidation: orchestration, process and query tier Merges the TorqX framework tier into kdbx-modules as the consolidation base, per RFC-0001 (docs/rfc-0001-torqx-kdbx-consolidation.md). Adds: - di.torq - the orchestrator replacing torq.q, plus its children di.torq.{servers,logroll} and the launcher at di/torq/bin (torqx.sh, torqx_init.q) - di.proc.{hdb,rdb,wdb,tickerplant,gateway} - the process types - di.subscriptions, di.dataaccess, di.tplogmgr - library tier - di.asyncdispatch, di.serverselect - tracked from their feature branches - CLAUDE.md, plus framework/DI sections appended to consistency.md and style.md - docs/reconciliation/*.md - per-module decision records Moves five modules into the agreed namespace hierarchy (RFC-0001 D1): di.toml -> di.util.toml di.config -> di.torq.config di.log -> di.util.log di.handlers -> di.torq.handlers + a `transform` phase (result-rewriting, pre -> exec -> transform -> post; existing phases untouched) di.depcheck -> di.torq.depcheck + hierarchy-aware namespace resolution, a pre-load on-disk VERSION manifest graph, and the di.timer contract aligned to the five keys di.torq consumes Each is the upstream implementation plus the additions recorded in docs/reconciliation/. References updated repo-wide. di.dbwrite, di.eodtime and di.pubsub gain a VERSION file and a `version` export: consumer manifests declare them, and di.torq.depcheck validates both a pre-load VERSION graph and a post-load session audit. Verified: 20 k4unit suites, 1327 checks, 0 failures, each in its own process; and the full stack boots and runs end to end - tickerplant -> rdb/wdb streaming, EOD writedown/sort/move into the hdb with rdb reload, and gateway scatter-gather plus getdata map-reduce across rdb and hdb. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 123 +++++++ consistency.md | 120 ++++++- di/api/api.md | 6 +- di/api/api.q | 2 +- di/asyncdispatch/VERSION | 1 + di/asyncdispatch/asyncdispatch.md | 251 ++++++++++++++ di/asyncdispatch/asyncdispatch.q | 327 ++++++++++++++++++ di/asyncdispatch/init.q | 16 + di/asyncdispatch/test.csv | 187 ++++++++++ di/compression/compression.md | 2 +- di/compression/compression.q | 2 +- di/dataaccess/VERSION | 1 + di/dataaccess/dataaccess.md | 90 +++++ di/dataaccess/dataaccess.q | 345 +++++++++++++++++++ di/dataaccess/deps.toml | 4 + di/dataaccess/init.q | 12 + di/dataaccess/test.csv | 139 ++++++++ di/dbwrite/VERSION | 1 + di/dbwrite/dbwrite.md | 4 +- di/dbwrite/dbwrite.q | 2 +- di/dbwrite/init.q | 7 +- di/depcheck/deps.q | 4 - di/depcheck/init.q | 9 - di/depcheck/test.csv | 183 ---------- di/eodtime/VERSION | 1 + di/eodtime/eodtime.md | 6 +- di/eodtime/init.q | 7 +- di/eodtime/test.csv | 4 +- di/handlers/init.q | 5 - di/log/init.q | 4 - di/pqx/pqx.md | 10 +- di/pqx/pqx.q | 2 +- di/proc/gateway/VERSION | 1 + di/proc/gateway/deps.toml | 9 + di/proc/gateway/gateway.md | 90 +++++ di/proc/gateway/gateway.q | 141 ++++++++ di/proc/gateway/init.q | 5 + di/proc/gateway/test.csv | 9 + di/{depcheck => proc/hdb}/VERSION | 0 di/proc/hdb/hdb.md | 108 ++++++ di/proc/hdb/hdb.q | 39 +++ di/proc/hdb/init.q | 5 + di/proc/hdb/test.csv | 30 ++ di/proc/hdb/test.q | 35 ++ di/proc/rdb/VERSION | 1 + di/proc/rdb/deps.toml | 5 + di/proc/rdb/init.q | 5 + di/proc/rdb/rdb.md | 121 +++++++ di/proc/rdb/rdb.q | 152 +++++++++ di/proc/rdb/test.csv | 9 + di/proc/tickerplant/VERSION | 1 + di/proc/tickerplant/deps.toml | 5 + di/proc/tickerplant/init.q | 5 + di/proc/tickerplant/test.csv | 44 +++ di/proc/tickerplant/test.q | 75 ++++ di/proc/tickerplant/tickerplant.md | 90 +++++ di/proc/tickerplant/tickerplant.q | 168 +++++++++ di/proc/wdb/VERSION | 1 + di/proc/wdb/deps.toml | 5 + di/proc/wdb/init.q | 5 + di/proc/wdb/test.csv | 9 + di/proc/wdb/wdb.md | 120 +++++++ di/proc/wdb/wdb.q | 230 +++++++++++++ di/pubsub/VERSION | 1 + di/pubsub/init.q | 7 +- di/serverselect/VERSION | 1 + di/serverselect/init.q | 19 ++ di/serverselect/integration.q | 277 +++++++++++++++ di/serverselect/serverselect.md | 240 +++++++++++++ di/serverselect/serverselect.q | 270 +++++++++++++++ di/serverselect/test.csv | 194 +++++++++++ di/subscriptions/VERSION | 1 + di/subscriptions/deps.toml | 3 + di/subscriptions/init.q | 5 + di/subscriptions/subscriptions.md | 74 ++++ di/subscriptions/subscriptions.q | 77 +++++ di/subscriptions/test.csv | 24 ++ di/subscriptions/test.q | 42 +++ di/torq/VERSION | 1 + di/torq/bin/torqx.sh | 358 ++++++++++++++++++++ di/torq/bin/torqx_init.q | 26 ++ di/torq/config/VERSION | 1 + di/{ => torq}/config/config.md | 100 +++--- di/{ => torq}/config/config.q | 40 +-- di/{ => torq}/config/init.q | 0 di/{ => torq}/config/test.csv | 16 +- di/torq/depcheck/VERSION | 1 + di/{ => torq}/depcheck/depcheck.md | 31 +- di/{ => torq}/depcheck/depcheck.q | 235 +++++++++---- di/torq/depcheck/deps.q | 4 + di/torq/depcheck/init.q | 8 + di/torq/depcheck/test.csv | 217 ++++++++++++ di/{ => torq}/depcheck/test_integration.csv | 6 +- di/torq/handlers/VERSION | 1 + di/{ => torq}/handlers/handlers.md | 22 +- di/{ => torq}/handlers/handlers.q | 89 +++-- di/torq/handlers/init.q | 7 + di/{ => torq}/handlers/test.csv | 36 +- di/{ => torq}/handlers/test_integration.csv | 6 +- di/torq/init.q | 5 + di/torq/logroll/VERSION | 1 + di/torq/logroll/init.q | 5 + di/torq/logroll/logroll.md | 172 ++++++++++ di/torq/logroll/logroll.q | 97 ++++++ di/torq/logroll/test.csv | 47 +++ di/torq/logroll/test.q | 84 +++++ di/torq/logroll/test_childinit.q | 24 ++ di/torq/servers/VERSION | 1 + di/torq/servers/init.q | 3 + di/torq/servers/servers.md | 130 +++++++ di/torq/servers/servers.q | 241 +++++++++++++ di/torq/servers/test.csv | 48 +++ di/torq/servers/test.q | 70 ++++ di/torq/settings/default.q | 1 + di/torq/settings/hdb.q | 1 + di/torq/test.csv | 53 +++ di/torq/test.q | 73 ++++ di/torq/torq.md | 264 +++++++++++++++ di/torq/torq.q | 255 ++++++++++++++ di/tplogmgr/VERSION | 1 + di/tplogmgr/init.q | 5 + di/tplogmgr/test.csv | 24 ++ di/tplogmgr/test.q | 90 +++++ di/tplogmgr/tplogmgr.md | 66 ++++ di/tplogmgr/tplogmgr.q | 72 ++++ di/util/log/VERSION | 1 + di/util/log/init.q | 10 + di/{ => util}/log/log.md | 14 +- di/{ => util}/log/log.q | 0 di/{ => util}/log/test.csv | 2 +- di/util/toml/VERSION | 1 + di/{ => util}/toml/init.q | 2 +- di/{ => util}/toml/test.csv | 8 +- di/{ => util}/toml/test.q | 6 +- di/{ => util}/toml/toml.md | 36 +- di/{ => util}/toml/toml.q | 36 +- docs/reconciliation/config.md | 68 ++++ docs/reconciliation/dataaccess.md | 95 ++++++ docs/reconciliation/dbwrite.md | 58 ++++ docs/reconciliation/depcheck.md | 77 +++++ docs/reconciliation/eodtime.md | 60 ++++ docs/reconciliation/handlers.md | 87 +++++ docs/reconciliation/log.md | 95 ++++++ docs/reconciliation/pubsub.md | 78 +++++ docs/reconciliation/servers.md | 64 ++++ docs/reconciliation/serverselect.md | 87 +++++ docs/reconciliation/toml.md | 50 +++ docs/rfc-0001-torqx-kdbx-consolidation.md | 240 +++++++++++++ style.md | 17 + 149 files changed, 8365 insertions(+), 500 deletions(-) create mode 100644 CLAUDE.md create mode 100644 di/asyncdispatch/VERSION create mode 100644 di/asyncdispatch/asyncdispatch.md create mode 100644 di/asyncdispatch/asyncdispatch.q create mode 100644 di/asyncdispatch/init.q create mode 100644 di/asyncdispatch/test.csv create mode 100644 di/dataaccess/VERSION create mode 100644 di/dataaccess/dataaccess.md create mode 100644 di/dataaccess/dataaccess.q create mode 100644 di/dataaccess/deps.toml create mode 100644 di/dataaccess/init.q create mode 100644 di/dataaccess/test.csv create mode 100644 di/dbwrite/VERSION delete mode 100644 di/depcheck/deps.q delete mode 100644 di/depcheck/init.q delete mode 100644 di/depcheck/test.csv create mode 100644 di/eodtime/VERSION delete mode 100644 di/handlers/init.q delete mode 100644 di/log/init.q create mode 100644 di/proc/gateway/VERSION create mode 100644 di/proc/gateway/deps.toml create mode 100644 di/proc/gateway/gateway.md create mode 100644 di/proc/gateway/gateway.q create mode 100644 di/proc/gateway/init.q create mode 100644 di/proc/gateway/test.csv rename di/{depcheck => proc/hdb}/VERSION (100%) create mode 100644 di/proc/hdb/hdb.md create mode 100644 di/proc/hdb/hdb.q create mode 100644 di/proc/hdb/init.q create mode 100644 di/proc/hdb/test.csv create mode 100644 di/proc/hdb/test.q create mode 100644 di/proc/rdb/VERSION create mode 100644 di/proc/rdb/deps.toml create mode 100644 di/proc/rdb/init.q create mode 100644 di/proc/rdb/rdb.md create mode 100644 di/proc/rdb/rdb.q create mode 100644 di/proc/rdb/test.csv create mode 100644 di/proc/tickerplant/VERSION create mode 100644 di/proc/tickerplant/deps.toml create mode 100644 di/proc/tickerplant/init.q create mode 100644 di/proc/tickerplant/test.csv create mode 100644 di/proc/tickerplant/test.q create mode 100644 di/proc/tickerplant/tickerplant.md create mode 100644 di/proc/tickerplant/tickerplant.q create mode 100644 di/proc/wdb/VERSION create mode 100644 di/proc/wdb/deps.toml create mode 100644 di/proc/wdb/init.q create mode 100644 di/proc/wdb/test.csv create mode 100644 di/proc/wdb/wdb.md create mode 100644 di/proc/wdb/wdb.q create mode 100644 di/pubsub/VERSION create mode 100644 di/serverselect/VERSION create mode 100644 di/serverselect/init.q create mode 100644 di/serverselect/integration.q create mode 100644 di/serverselect/serverselect.md create mode 100644 di/serverselect/serverselect.q create mode 100644 di/serverselect/test.csv create mode 100644 di/subscriptions/VERSION create mode 100644 di/subscriptions/deps.toml create mode 100644 di/subscriptions/init.q create mode 100644 di/subscriptions/subscriptions.md create mode 100644 di/subscriptions/subscriptions.q create mode 100644 di/subscriptions/test.csv create mode 100644 di/subscriptions/test.q create mode 100644 di/torq/VERSION create mode 100755 di/torq/bin/torqx.sh create mode 100644 di/torq/bin/torqx_init.q create mode 100644 di/torq/config/VERSION rename di/{ => torq}/config/config.md (76%) rename di/{ => torq}/config/config.q (82%) rename di/{ => torq}/config/init.q (100%) rename di/{ => torq}/config/test.csv (92%) create mode 100644 di/torq/depcheck/VERSION rename di/{ => torq}/depcheck/depcheck.md (63%) rename di/{ => torq}/depcheck/depcheck.q (61%) create mode 100644 di/torq/depcheck/deps.q create mode 100644 di/torq/depcheck/init.q create mode 100644 di/torq/depcheck/test.csv rename di/{ => torq}/depcheck/test_integration.csv (85%) create mode 100644 di/torq/handlers/VERSION rename di/{ => torq}/handlers/handlers.md (94%) rename di/{ => torq}/handlers/handlers.q (67%) create mode 100644 di/torq/handlers/init.q rename di/{ => torq}/handlers/test.csv (83%) rename di/{ => torq}/handlers/test_integration.csv (93%) create mode 100644 di/torq/init.q create mode 100644 di/torq/logroll/VERSION create mode 100644 di/torq/logroll/init.q create mode 100644 di/torq/logroll/logroll.md create mode 100644 di/torq/logroll/logroll.q create mode 100644 di/torq/logroll/test.csv create mode 100644 di/torq/logroll/test.q create mode 100644 di/torq/logroll/test_childinit.q create mode 100644 di/torq/servers/VERSION create mode 100644 di/torq/servers/init.q create mode 100644 di/torq/servers/servers.md create mode 100644 di/torq/servers/servers.q create mode 100644 di/torq/servers/test.csv create mode 100644 di/torq/servers/test.q create mode 100644 di/torq/settings/default.q create mode 100644 di/torq/settings/hdb.q create mode 100644 di/torq/test.csv create mode 100644 di/torq/test.q create mode 100644 di/torq/torq.md create mode 100644 di/torq/torq.q create mode 100644 di/tplogmgr/VERSION create mode 100644 di/tplogmgr/init.q create mode 100644 di/tplogmgr/test.csv create mode 100644 di/tplogmgr/test.q create mode 100644 di/tplogmgr/tplogmgr.md create mode 100644 di/tplogmgr/tplogmgr.q create mode 100644 di/util/log/VERSION create mode 100644 di/util/log/init.q rename di/{ => util}/log/log.md (95%) rename di/{ => util}/log/log.q (100%) rename di/{ => util}/log/test.csv (99%) create mode 100644 di/util/toml/VERSION rename di/{ => util}/toml/init.q (58%) rename di/{ => util}/toml/test.csv (95%) rename di/{ => util}/toml/test.q (86%) rename di/{ => util}/toml/toml.md (80%) rename di/{ => util}/toml/toml.q (77%) create mode 100644 docs/reconciliation/config.md create mode 100644 docs/reconciliation/dataaccess.md create mode 100644 docs/reconciliation/dbwrite.md create mode 100644 docs/reconciliation/depcheck.md create mode 100644 docs/reconciliation/eodtime.md create mode 100644 docs/reconciliation/handlers.md create mode 100644 docs/reconciliation/log.md create mode 100644 docs/reconciliation/pubsub.md create mode 100644 docs/reconciliation/servers.md create mode 100644 docs/reconciliation/serverselect.md create mode 100644 docs/reconciliation/toml.md create mode 100644 docs/rfc-0001-torqx-kdbx-consolidation.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..730728bf --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,123 @@ +# TorqX — orientation for Claude + +TorqX decomposes the TorQ kdb+ framework into standalone **`di.*` kdb-x modules** wired by +**dependency injection**, replacing the monolithic `torq.q` bootstrap with `di.torq`. It is the +framework/reference-app side of the [TorQ Modularisation Plan](https://data-intellect.atlassian.net/wiki/spaces/TK/pages/2375450629) +(design + findings: [TorqX POC status page](https://data-intellect.atlassian.net/wiki/spaces/TK/pages/2646409222)). +This repo (**`kdbx-modules`**) is the **consolidation base** per **RFC-0001** (agreed): the TorqX +orchestration / process / query tier is being merged in under the agreed namespace hierarchy. The +migration is **phased** — see [`docs/rfc-0001-torqx-kdbx-consolidation.md`](docs/rfc-0001-torqx-kdbx-consolidation.md). +New framework/process modules land in the hierarchy now; the existing flat utility modules are +renamed into it later in one coordinated change (RFC phase 5), so expect flat and hierarchical +names to coexist during the transition. + +**Read `consistency.md` and `style.md` before writing module code** — they are the authoritative +conventions. This file is the map + the environment realities + the q traps that aren't obvious. + +## Repo layout + +Modules live under `di/`, one directory per module, resolved on `QPATH`. A module is a directory +containing `init.q` (which `\l ::`-loads its source and defines an `export:([...])` dict), plus a +`VERSION`, a `.md`, `test.csv`/`test.q` (k4unit), and an optional `deps.toml`. + +TorqX groups modules into a hierarchy (kdb-x resolves `di.a.b` → `di/a/b/`; a parent can be a +module *and* hold children): + +- `di.proc.*` — process types: `hdb rdb wdb tickerplant gateway` +- `di.torq` (+ children) — the orchestrator and the machinery it owns: + `di.torq.{config,depcheck,servers,handlers,logroll}`; the launcher ships at `di/torq/bin/` + (`torqx.sh`, `torqx_init.q`) +- `di.util.*` — standalone utilities: `toml`, `log` +- flat `di.*` — the reusable library layer (`tplog subscriptions dataaccess`) and everything + **vendored** from `kdbx-modules` branches (`asyncdispatch serverselect pubsub dbwrite eodtime`) + or **external** (`timer tz tplogutils k4unit`). Vendored modules keep their upstream flat names + so they re-sync cleanly — do not rename or restyle them. + +## Environment + +Module resolution and tests need: + +- `QPATH="::$HOME/.kx/mod"` — colon-separated, first match wins; `di.a.b` + looks for `/di/a/b/init.`. `$HOME/.kx/mod` provides KX modules incl. `kx.log`. +- `QLIC="$HOME/.kx"` — must resolve the **corporate** `k4.lic`. The community `kc.lic` has a + connection/process cap that makes the spawn-heavy test suites fail once enough accumulate; if a + community licence is present, rename it so `k4.lic` wins. +- `QHOME="$HOME/.kx"`. +- Running the **stack** (not needed for unit tests) also uses `TORQXHOME` (framework checkout), + `TORQXAPPHOME`/`TORQXAPPCONFIG` (the app), `TORQXDATAHOME` (runtime data), `TORQXSTACKID`. See + an app's `setenv.sh` (e.g. `TorqX-POC/setenv.sh`). + +## Running tests (k4unit) + +Run **with the repo root as the working directory** — each `test.csv` loads its fixtures with a +cwd-relative `system "l di//test.q"`. + +```q +q)k4u:use`di.k4unit +q)(k4u`moduletest)`di.torq.servers / runs the module's test.csv +q)show (k4u`getresults)[] / KUTR table; rows with ok=0b failed +``` + +- Index the returned handle with **brackets** (`k4u`moduletest`) — a dot-call (`k4u.moduletest`) + on a module you just `use`d can fail until the frame returns to top level. +- **Spawn-heavy suites** (`di.asyncdispatch`, `di.pubsub`, `di.torq.servers`, `di.torq`, …) spawn + real child q processes on real ports. They need the corporate licence **and**, under a sandbox, + permission to `bind()` — run them **unsandboxed**. `di.torq`'s tests also need `TORQXHOME` set. +- You **cannot** host an interactive q in a headless harness to test tty-dependent behaviour + (`script`/`pty` make q enter the REPL and hang). Prove such logic over IPC against a real + tty-attached process, or via deterministic stdin-inheritance. +- Known-red: `di.tplog`'s 4 corruption tests fail purely as an artefact of the shared + `kdbx-modules` checkout's branch naming (`di.tplog` vs `di.tplogutils`); runtime is unaffected. + +## Running the stack + +From an app directory, after `source ./setenv.sh`: + +```bash +torqx.sh start|stop|restart|status [procname|all] # at $TORQXHOME/di/torq/bin, on PATH via setenv +torqx.sh start --tmux # dev mode: attachable tmux session per process (devstart/devattach) +torqx.sh export-systemd # production: one systemd --user unit per process.csv row +``` + +## Conventions you must know (details in `consistency.md`) + +- **DI:** framework/process modules take `init[config;deps]`; store deps, call through `.z.m`. +- **Inject cross-cutting singletons (`log`/`timer`/`handlers`/`servers`); `use` libraries.** + Injected `init`s must be idempotent. +- **Module-namespace write boundary:** a `use`-loaded module's bare *writes* (and `-11!` replay) + land in its private namespace — maintain root tables / publish root IPC names via + `@[`.;name;…]` / `set[`.ns.fn;…]`. +- **Versioning:** `VERSION` + per-module `deps.toml`; `di.torq.depcheck` validates a transitive + manifest graph at startup. + +## q gotchas (these have each cost real debugging time) + +- **Lambda bracket spacing:** `{[e] -2 x}` needs the space after `]`; `{[e]-2 x}` misparses. +- **`system` execs the command DIRECTLY — no shell.** No `&&`, `||`, pipes, `cd`, `~`, globs. + Wrap in `sh -c "…"` when you need shell features. +- **Reserved-name shadowing fails, sometimes at load:** don't name a local/param `log`, `ss`, + `sv`, `string`, `cut`, `tables`, etc. (`sv:…` throws `'sv` on load). Use `srv`, `lg`, …. +- **Parse tree: a bare symbol is a COLUMN reference.** In functional qSQL a bare `` `date `` is + the column; a literal symbol value must be enlisted — `($;enlist`date;`time)` casts `time` to + the *type* date. +- **Single-char string literals are atomised** at compile time (type `-10h`); `enlist` restores a + 1-char vector. Runtime-built 1-char strings are already `10h` — don't blindly `enlist` (that + double-wraps). Only `enlist` a genuine atom: `$[0>type x;enlist x;x]`. +- **Two 1-char string literals coalesce:** `("1";"2")` becomes the 2-char vector `"12"`; use + `(enlist"1";enlist"2")` for a 2-item list. +- **`and`/`or` do not short-circuit** and evaluate both sides eagerly — if one side can throw, + guard with nested `if[]`, not a combined condition. +- **`` `$ ``, `string`, and casts are not idempotent** — they throw on already-converted input. + Type-check first: `assym:{$[11h=abs type x;x;`$x]}`. +- **Right-to-left, flat precedence:** `not a or b` parses as `not[a or b]`. Fence explicitly. +- **Deferred-sync IPC is one message list:** `neg[h](`fn;a;b); h[]` — NOT `neg[h] . (`fn;a;b)` + (that `.`-applies a monadic handle with N args → `'length`). +- **Dict coalescing:** seed an accumulator dict with `` enlist[`]!enlist(::) `` so `,:` will widen + the value type instead of refusing. +- **Shell is zsh** (in tooling): unquoted `$var` does *not* word-split — use `find … | while IFS= read -r f` for file loops, not `for f in $files`. + +## Module resolution recap + +`QPATH` colon-separated, first wins; `di.a.b` → `/di/a/b/init.q`. A module = a dir with +`init.q` + an `export:([…])` dict. Parents can be modules too; `use`ing a child does not load the +parent (so `di.torq` being both orchestrator and namespace parent is safe). diff --git a/consistency.md b/consistency.md index 1c2cb242..000e0f3c 100644 --- a/consistency.md +++ b/consistency.md @@ -46,7 +46,7 @@ init:{[deps] / mymodule.init[enlist[`log]!enlist logdep] logdict:$[99h=type deps;$[(`log in key deps) and not (::)~deps`log;deps`log;()!()];()!()]; if[not count logdict; - '"di.mymodule: log dependency is required; pass `info`warn`error functions - see di.log or refer to confluence documentation"; + '"di.mymodule: log dependency is required; pass `info`warn`error functions - see di.util.log or refer to confluence documentation"; ]; .z.m.loginfo:logdict`info; .z.m.logwarn:logdict`warn; @@ -58,18 +58,128 @@ myfunc:{[x] }; ``` -Callers provide a dict of functions. Use `di.log` if no custom logger is needed: +Callers provide a dict of functions. Use `di.util.log` if no custom logger is needed: ```q -logging:use`di.log +logging:use`di.util.log logdep:`info`warn`error!(logging.info;logging.warn;logging.error) mymodule.init[enlist[`log]!enlist logdep] ``` -`di.log`'s `logdict` skips building that dict by hand — it's already wrapped in the shape `init` +`di.util.log`'s `logdict` skips building that dict by hand — it's already wrapped in the shape `init` expects: ```q -logging:use`di.log +logging:use`di.util.log mymodule.init[logging.logdict] ``` + +--- + +# Framework & DI conventions (surfaced by the TorqX framework tier) + +> The sections below **extend** the base guide with conventions surfaced while building the +> orchestration / process tier (`di.torq` and the process modules). They are additive to the +> rules above; where one refines an existing rule (e.g. the `init` signature) that is called out. +> Provenance: distilled from the TorqX POC (see the "TorqX POC: Status & Design Findings" +> Confluence page). Some points are pending formal alignment with `kdbx-modules` — flagged inline. + +## `init` signature: `init[config;deps]` for framework/process modules + +The base guide shows `init[deps]`. That holds for pure **library** modules. **Framework and +process modules** — anything `di.torq` orchestrates (the process types, and the injected core +modules) — take **`init[config;deps]`**: + +- `config` — the merged settings dictionary for this process, produced by `di.torq.config`'s cascade + and distributed by `di.torq`. Read a tunable with a presence check: + `$[`somekey in key config;config`somekey;default]`. +- `deps` — the injected-capability dict, exactly as in the base guide. + +A module that needs no settings may ignore `config`, but should still accept it so every module +is called through one convention. + +Storage: the base guide stores each injected function individually (`.z.m.loginfo` …). Framework +modules may instead store the **whole dep dict** and index it at the call site +(`.z.m.log:deps`log;` then `.z.m.log[`info][`ctx;"msg"]`). Either is fine; be consistent within a +module. Both still route every call through `.z.m`. + +## What to inject vs what to `use` + +Two kinds of dependency, kept deliberately distinct: + +- **Injected** (passed in `deps`, built once by `di.torq`) — cross-cutting, substitutable + **singletons with a lifecycle**: `log`, `timer`, `handlers`, `servers`. There must be exactly + one per process, callers may want to swap the implementation, and their `init` has side effects + (handler/timer registration) that must run once. Contract key sets: + - `log` → `` `info`warn`error `` (each `{[ctx;msg]}`) + - `timer` → `` `addjob`deletejobs`enablejobs`disablejobs`getactivejobs `` + - `handlers` → `` `register`remove`list `` + - `servers` → `` `startup`getservers`gethandlebytype`waitfortype `` (its `init` is owned by + `di.torq`; consumers call `startup` with their own connection list) +- **`use`-imported** (a real, greppable module dependency) — stateless / process-local + **libraries** with no substitution need: e.g. `di.tplog`, `di.subscriptions`, `di.dataaccess`, + `di.pubsub`, `di.dbwrite`. + +**Rule of thumb: inject cross-cutting singletons; `use` libraries.** `use` is the default; reach +for injection only where there is shared state, a single lifecycle, or a substitution seam. + +An injected module's `init` must be **idempotent** — guard the one-time registrations (a +`registered` flag) so a second `init` in the same process can't double-register a `.z.pc` handler +or a timer job. + +## The module-namespace write boundary + +A `use`-loaded module runs in its own private namespace. The consequence bites everyone who +maintains root state, so treat it as a contract: + +- **Reads** of a bare name fall through to root — `select from trade` reads the root `trade`. +- **Writes** — `set`, bare `insert`/`upsert`, and anything run under `-11!` replay — land in the + module's **private** namespace, **not** root. + +So a module that must maintain a **root** table, or publish a **root-level IPC entry point**, must +target root explicitly: + +```q +@[`.;`upd;:;updfn]; / publish a root-callable upd +@[`.;t;{[tab;d] tab upsert d}[;x]]; / upsert into the ROOT table t (works under -11! too) +set[`.hdb.reload;reloadfn]; / publish a root IPC function a peer can call by name +``` + +A subscriber's root `upd` (invoked by the tickerplant and by `-11!` log replay) must be written +this way, or replayed/pushed rows silently vanish into the module namespace. + +## Versioning & dependency manifests + +Extends "module Contents". In addition to code / docs / tests, every module ships: + +- a plain-text **`VERSION`** file (semver), read into the exported `version`; +- an optional **`deps.toml`** declaring the minimum versions of the modules it `use`s: + ```toml + [dependencies] + "di.serverselect" = "0.2.0" + ``` + +`di.torq.depcheck` validates these at startup — the app's own `deps.toml`, **plus** a manifest-graph +walk from the process's entry module through each peer's own `deps.toml` (transitive, on-disk +reads only, loads no module code). A missing `deps.toml` is a silent no-op, so adoption is +incremental. This catches "upgraded one module but not the peer it now needs" as a clear startup +error instead of a cryptic runtime one. + +## Module namespace hierarchy *(agreed — RFC-0001, phased rollout)* + +TorqX groups modules into a namespace hierarchy rather than flat `di.*`: + +- `di.proc.*` — deployable process types (hdb, rdb, wdb, tickerplant, gateway) +- `di.torq.*` — the orchestrator plus the framework machinery it owns (config, depcheck, servers, + handlers, logroll) +- `di.util.*` — standalone utilities usable outside a di.torq app (toml, log) +- flat `di.*` — the reusable library layer and all vendored / upstream modules + +kdb-x supports this: `di.a.b` resolves to `di/a/b/`, and a parent (`di.torq`) can be both a +loadable module and a parent of children (loading a child does not load the parent). + +> **Status:** the hierarchy is the **agreed** target scheme (RFC-0001). Rollout is **phased**: +> new framework/process modules (`di.torq.*`, `di.proc.*`, `di.util.*`) land in the hierarchy now; +> the existing flat utility modules migrate in one coordinated change later (RFC phase 5), *after* +> the in-flight branches are drained/rebased. So flat and hierarchical names coexist for now — do +> **not** pre-emptively rename existing flat modules or open branches ahead of phase 5. diff --git a/di/api/api.md b/di/api/api.md index f58a1c5f..baa66d3e 100644 --- a/di/api/api.md +++ b/di/api/api.md @@ -17,12 +17,12 @@ depend on di.api. `init` must be called before any other function. The `log` dependency is **required** — there is no fallback, and the module does no adaptation. The `log` value must already be a binary -`` `info`warn`error!{[c;m]} `` dict (context symbol, message string), built from `di.log` or +`` `info`warn`error!{[c;m]} `` dict (context symbol, message string), built from `di.util.log` or hand-rolled; a raw monadic `kx.log` instance must be wrapped by the caller first. ```q api:use`di.api -logger:use`di.log +logger:use`di.util.log api.init[enlist[`log]!enlist `info`warn`error!(logger.info;logger.warn;logger.error)] ``` @@ -85,7 +85,7 @@ see only a process's top-level glue, not the module logic they exist to inspect. | `whereami` | Reverse-looks-up a function value to its name via the root scan — returns nothing for a function that lives inside a module (i.e. the usual error-trap case). | | `fullapi` (namespace scan) | The scan-and-left-join-`detail` model does not apply; `getapi`/`find` serve the registry directly. | | `mem` / `m` | Memory sizing belongs to `di.memstats`. | -| `exportconfig` / `exportallconfig` / `torqnamespaces` | A faithful port needs config **values** (di.config `getmodule`) joined with **descriptions** (di.api `getapi`/`find`). di.config and di.api are both standalone and don't depend on each other, so the join belongs in **di.torq** (it has both). It is a **di.torq-era task**, not a di.config change: di.config's `getmodule` already returns per-namespace values; the missing piece is pairing them with the api descriptions across namespaces. | +| `exportconfig` / `exportallconfig` / `torqnamespaces` | A faithful port needs config **values** (di.torq.config `getmodule`) joined with **descriptions** (di.api `getapi`/`find`). di.torq.config and di.api are both standalone and don't depend on each other, so the join belongs in **di.torq** (it has both). It is a **di.torq-era task**, not a di.torq.config change: di.torq.config's `getmodule` already returns per-namespace values; the missing piece is pairing them with the api descriptions across namespaces. | ## Hard dependencies diff --git a/di/api/api.q b/di/api/api.q index 8e156518..0394cf4a 100644 --- a/di/api/api.q +++ b/di/api/api.q @@ -8,7 +8,7 @@ detailschema:([name:`u#`symbol$()] public:`boolean$(); descrip:(); params:(); re init:{[deps] / wire the injected logger (required, no fallback) and start with an empty registry. deps: a `log - / key holding a binary `info`warn`error dict of {[c;m]} loggers (di.log or hand-rolled; a monadic + / key holding a binary `info`warn`error dict of {[c;m]} loggers (di.util.log or hand-rolled; a monadic / kx.log instance must be wrapped first). e.g. di.api.init[enlist[`log]!enlist logdep] if[99h<>type deps; '"di.api: deps must be a dict with a `log key"]; diff --git a/di/asyncdispatch/VERSION b/di/asyncdispatch/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/asyncdispatch/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/asyncdispatch/asyncdispatch.md b/di/asyncdispatch/asyncdispatch.md new file mode 100644 index 00000000..869aea4f --- /dev/null +++ b/di/asyncdispatch/asyncdispatch.md @@ -0,0 +1,251 @@ +# di.asyncdispatch + +Async scatter-gather query coordinator for kdb-x gateway processes. Queues client queries, dispatches them to available backend processes by servertype, collects per-server results, applies a join function, and replies to the client — with timeout management and correct error propagation if a backend disconnects mid-query. + +Routing (deciding which servertypes satisfy a query) is `di.serverselect`'s responsibility, but **`di.serverselect` is not a dependency** — this module dispatches a resolved servertype list to whatever backends its *server source* reports. That source is pluggable with a default: by default it is asyncdispatch's own registry (populate it with `addserver`), or you point it at `di.serverselect`'s output via `setavailableservers`. Either works standalone; neither is required. + +--- + +## Features + +- Queue and dispatch async client queries to multiple backend process types simultaneously (scatter-gather) +- Collect per-server results and apply a caller-supplied join function once all slots are filled +- Timeout expired queries with configurable per-query timespan via `checktimeout` +- Handle backend disconnects mid-query — errors in-flight queries and queued queries that can no longer be satisfied +- Track connected clients and clean up orphaned queries on client disconnect +- Support synchronous deferred response mode (`-30!`) alongside the default async mode +- Pluggable server source with a default — dispatch against the built-in registry (`addserver`) by default, or point it at `di.serverselect`'s output (or any source) via `setavailableservers`; `di.serverselect` is a composable option, never a dependency +- Accept fully pluggable scheduler (`setgetnextqueryid`), routing (`setavailableservers`), reply formatter (`setformatresponse`), and callback symbols (`setcallbacks`) — swap without touching core dispatch logic + +--- + +## Dependencies + +| Dependency | Key | Required | Description | +|---|---|---|---| +| logger | `` `log `` | yes | `info`, `warn`, `error` — each binary `{[c;m]}` where `c` is a symbol context and `m` is a string | + +The `log` dependency must be passed to `init` inside the `deps` dict. The module throws immediately if it is absent or missing any of the three required keys. All three are required since the module calls `info`, `warn`, and `error`. The dict passed in must already match the binary `{[c;m]}` contract — the module does not detect or adapt other shapes (e.g. a raw `kx.log` instance, which is monadic). If you want to use `kx.log`, load it and write your own `{[c;m]}` wrapper around it before passing it in. + +--- + +## Initialisation + +`init[deps]` takes a single dictionary combining the `log` dependency with any configuration overrides. + +| Key | Required | Default | Description | +|---|---|---|---| +| `` `log `` | yes | — | Binary log dep — `info`, `warn`, `error` functions each `{[c;m]}` | +| `` `errorprefix `` | no | `"error: "` | String prepended to all error messages sent back to clients | +| `` `querykeeptime `` | no | `0D00:30` | How long `removequeries` retains finished query rows | +| `` `clearinactivetime `` | no | `0D01:00` | How long `removeinactive` retains disconnected server rows | +| `` `synccallsallowed `` | no | `0b` | Whether `execquery[...;1b]` (deferred sync mode) is permitted | + +Housekeeping — `checktimeout`, `removequeries`, `removeinactive`, and `removeclients` — is the caller's responsibility. Wire them into your gateway's timer after `init`. The configured default age parameters are accessible as `querykeeptime` and `clearinactivetime` via module state. + +--- + +## Exported Functions + +### `init[deps]` +Initialise the module. Validates the log dependency and applies config overrides. +```q +ad.init[enlist[`log]!enlist logdep] +``` + +### `addserver[handle;servertype]` +Register a backend connection into the **built-in (default) server source**. `handle`: open int handle. `servertype`: symbol identifying the process type (e.g. `` `rdb ``, `` `hdb ``). Use this when asyncdispatch owns the server list; to source servers from `di.serverselect` instead, leave `addserver` unused and inject via `setavailableservers`. +```q +ad.addserver[hopen`:backend1:5001;`rdb] +``` + +### `removeserverhandle[handle]` +Call from `.z.pc` for **backend** handles. Errors any in-flight or queued queries that depended on this server, marks the server `active:0b`, and triggers `runnextquery`. +```q +.z.pc:{ad.removeserverhandle[.z.w];ad.removeclienthandle[.z.w]} +``` + +### `addclientdetails[handle]` +Record client identity on connect. Call from `.z.po`. +```q +.z.po:{ad.addclientdetails[.z.w]} +``` + +### `removeclienthandle[handle]` +On client disconnect, mark their pending queries errored so result slots are not leaked. Call from `.z.pc`. +```q +.z.pc:{ad.removeserverhandle[.z.w];ad.removeclienthandle[.z.w]} +``` + +### `addserverresult[qid;data]` +Called when a backend posts back a successful result. Fills the result slot, frees the server, triggers `runnextquery`, and — once all slots for the query are received — applies the join function and replies to the client. +```q +// called by serverexecute on the backend; not typically called directly +``` + +### `addservererror[qid;err]` +Called when a backend posts back an error. Sends the error to the client and finishes the query. +```q +// called by serverexecute on the backend; not typically called directly +``` + +### `execquery[query;servertype;join;postback;timeout;sync]` +Public entry point. Validates sync constraints, enqueues the query, and triggers dispatch. + +| Argument | Type | Description | +|---|---|---| +| `query` | any | Payload passed to `value` on the backend | +| `servertype` | symbol list | One symbol per required backend type, e.g. `` enlist`rdb `` | +| `join` | function | Applied to the list of per-server results once all are received | +| `postback` | list or `()` | `()` for a plain reply; `(function;extra_args...)` to wrap the reply | +| `timeout` | timespan | `0Wn` for no timeout | +| `sync` | boolean | `1b` for deferred sync via `-30!`; `0b` for async | + +```q +ad.execquery["select count i by sym from trade";enlist`rdb;raze;();0Wn;0b] +``` + +### `execqueryto[replyto;query;servertype;join;postback;timeout;sync]` +Variant of `execquery` with an explicit reply target. Pass `replyto:0Ni` to invoke the postback locally via `value` instead of IPC-sending to a handle. Pass any valid int handle to route the reply to a specific process regardless of `.z.w`. Used when the caller is in the same process as the gateway (e.g. `di.dataaccess` dispatching shards). + +| Argument | Type | Description | +|---|---|---| +| `replyto` | int | `0Ni` for local in-process invocation; any int handle to IPC-send to a specific target | +| `query` | any | Payload passed to `value` on the backend | +| `servertype` | symbol list | One symbol per required backend type | +| `join` | function | Applied to the list of per-server results once all are received | +| `postback` | list | Required when `replyto` is `0Ni` — `(function;extra_args...)` invoked locally; `()` permitted for non-local targets | +| `timeout` | timespan | `0Wn` for no timeout | +| `sync` | boolean | Must be `0b` when `replyto` is `0Ni`; sync not supported for local invocation | + +```q +// di.dataaccess wiring: shard result delivered locally to da.shardresult +ad.execqueryto[0Ni;shardquery;servertypes;raze;(`da.shardresult;reqid);0Wn;0b] +``` + +### `checktimeout[]` +Scan the queue for queries past their timeout, send a timeout error to each client, and mark them complete. Wire into your gateway's timer — every few seconds is typical. +```q +// in gateway timer +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] +``` + +### `removequeries[age]` +Purge completed `queryqueue` rows older than `age`. Prevents unbounded growth. +```q +// default age is querykeeptime (0D00:30) +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] +``` + +### `removeinactive[age]` +Purge `servers` rows for backends that have been disconnected longer than `age`. Prevents unbounded growth. +```q +// default age is clearinactivetime (0D01:00) +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] +``` + +### `removeclients[age]` +Purge `clients` rows older than `age`. The `clients` table is appended to on every client connect (`addclientdetails`) for audit and is not otherwise pruned, so wire this into the timer to prevent unbounded growth. Choose `age` to match your audit retention requirements. +```q +// retain one day of client audit history +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] +``` + +### `setformatresponse[f]` +Override the reply formatter applied before a result or error is sent to the client. `f` must be `{[status;sync;result]}`. Note: `formatresponse` is only applied on the remote IPC path — queries dispatched via `execqueryto` with `replyto:0Ni` invoke the postback directly and bypass this formatter. +```q +ad.setformatresponse[{[status;sync;result]result}] +``` + +### `setcallbacks[resfn;errfn]` +Update the callback symbols used by `serverexecute`. Required when the module is mounted under a non-default namespace — point these at wherever `addserverresult` and `addservererror` are visible on the backend processes. +```q +ad.setcallbacks[`.gw.dispatch.addserverresult;`.gw.dispatch.addservererror] +``` + +### `setavailableservers[f]` +Replace the **server source** — the function dispatch uses to find backends. `f` is `{[excludeinuse]}` and must return a table with `handle` and `servertype` columns. This is the seam for running against `di.serverselect` (or any external source) **without a dependency and without copying its registry**: by default the source reads asyncdispatch's own registry (`addserver`), and you override it to read serverselect instead. +```q +// default (built-in registry) — equivalent to not calling this at all +ad.setavailableservers[{[eu] $[eu; select from servers where active, not inuse; select from servers where active]}] + +// compose with di.serverselect (not a dependency — just its output as the source) +srvsel:use`di.serverselect +ad.setavailableservers[{[eu] select handle, servertype from srvsel.getservers[`servertype;`;()!()]}] +``` +Result routing does **not** depend on the source — a returning handle is matched to its servertype from the query's own dispatch record — so an injected source needs no registration in asyncdispatch. Note `inuse` throttling applies only to the built-in registry; an external source is expected to do its own idle/selection (e.g. serverselect's `roundrobin`), and the `excludeinuse` flag is a hint such a source may ignore. + +### `setgetnextqueryid[f]` +Inject a custom scheduling strategy. `f` must be niladic and return a 0- or 1-row table with the `queryqueue` schema. +```q +// priority queue example - highest-priority query first +ad.setgetnextqueryid[{1 sublist `priority xdesc 0!select from .z.m.queryqueue where null returntime}] +``` + +--- + +## Usage Example + +```q +// log dep must already match the binary {[c;m]} contract - write your own, or use di.util.log: +// logging:use`di.util.log +// ad.init[logging.logdict] +logdep:`info`warn`error!({[c;m]};{[c;m]};{[c;m]}) + +timer:use`di.timer +timer.init[()!()] + +ad:use`di.asyncdispatch +ad.init[enlist[`log]!enlist logdep] + +// point backends' callbacks at this module's mount point on this process +ad.setcallbacks[`ad.addserverresult;`ad.addservererror] + +// register backend connections as they connect +ad.addserver[hopen`:backend1:5001;`rdb] +ad.addserver[hopen`:backend2:5002;`hdb] + +// wire client and server connection/disconnection handlers +.z.po:{ad.addclientdetails[.z.w]} +.z.pc:{ad.removeserverhandle[.z.w];ad.removeclienthandle[.z.w]} + +// wire housekeeping into the gateway timer +timer.addjob.default[`asyncdispatch.checktimeout;{ad.checktimeout[]};();5i;1] +timer.addjob.default[`asyncdispatch.removequeries;{ad.removequeries[0D00:30]};();300i;1] +timer.addjob.default[`asyncdispatch.removeinactive;{ad.removeinactive[0D01:00]};();300i;1] +timer.addjob.default[`asyncdispatch.removeclients;{ad.removeclients[1D]};();300i;1] + +// a client calls this asynchronously: +// execquery dispatches to rdb and hdb in parallel, razes results, replies to client +ad.execquery[("select count i by sym from trade";"select count i by sym from trade");`rdb`hdb;raze;();0Wn;0b] + +// synchronous deferred mode (requires synccallsallowed:1b in deps) +ad.execquery["select count i by sym from trade";enlist`rdb;raze;();0Wn;1b] +``` + +--- + +## Running Tests + +```q +k4unit:use`di.k4unit +k4unit.moduletest`di.asyncdispatch +``` + +116 tests. Requires a `q` binary in `PATH` — the test suite starts two real backend processes on dynamically selected free ports and exercises the full dispatch lifecycle over live IPC connections. No TorQ installation or special libraries required. Covers: server registry, FIFO scheduling, full IPC round-trip with join and reply, backend error path via real IPC callback (`addservererror`), join-failure path (throwing join function flagged as error), postback wrapping (`tosend` tuple construction), multi-servertype scatter-gather with two backends dispatched in parallel and results joined, checktimeout, removequeries, removeinactive, removeclients audit-row purge, removeserverhandle with orphaned query cleanup, client tracking, in-flight server release on client disconnect, all pluggable hook setters, and local in-process reply path via `execqueryto` (success, backend error, timeout, and non-null explicit replyto variants). + +--- + +## Notes + +- Housekeeping (`checktimeout`, `removequeries`, `removeinactive`, `removeclients`) is the caller's responsibility — the gateway process already has a timer running and is better placed to decide intervals. Wire all four after `init`; see the usage example above +- When `checktimeout` fires for a query that is already in-flight (dispatched to a backend but not yet answered), the client receives the timeout error and the query is marked done, but the backend that received the dispatch remains `inuse:1b` until it eventually replies. A slow-but-alive backend holds its dispatch slot until `addserverresult` or `addservererror` fires; a permanently hung backend holds it until `removeserverhandle` fires on disconnect. Size backend pools and timeouts with this in mind — a run of timeouts against a stuck backend will not free its slot on timeout alone +- `.z.M.` is used for in-place mutation of tables (`upsert`, `insert`, `update from`, `delete from`) and `.z.m.:value` for whole-variable reassignment — the same convention used by `di.cache` +- Module globals referenced inside q-sql expressions (WHERE conditions, UPDATE SET values) must use the `.z.m.varname` form since q-sql evaluates column expressions in the calling context rather than the module namespace +- `servertype` in `queryqueue` and `addquery` is a list of servertype symbols — one per required backend type. Pass `` enlist`rdb `` for single-server queries, `` `rdb`hdb `` for scatter-gather across two types +- `setcallbacks` must be called before any queries are dispatched if the module is mounted under a non-default path — `serverexecute` reads `resultcallback` and `errorcallback` by bare name on the backend process and posts back to whatever symbols they resolve to +- This module opens and accepts no connections itself — `addserver` and the `.z.po`/`.z.pc` wiring are the consumer's responsibility, keeping the module dependency-free and testable in-process +- All three log keys (`info`, `warn`, `error`) are required — the module calls `info` on server/client connect and init, `warn` on disconnect and timeout, and `error` on backend error and join failure +- `execqueryto` with `replyto:0Ni` invokes the postback locally via `value` — the postback head symbol must be mount-qualified (e.g. `` `da.shardresult ``) since bare exported names are not globals. This is the same resolution mechanism used by `setcallbacks` +- Local queries store `clienth:0Ni` and are not matched by `removeclienthandle` — the in-process caller owns disconnect cleanup for its own requests +- `setformatresponse` overrides only apply to the remote IPC path — local invocation via `execqueryto[0Ni;...]` calls the postback directly without applying `formatresponse`. The default `formatresponse` is a pass-through for async, so this is transparent by default; consumers that override it should not combine that with local invocation diff --git a/di/asyncdispatch/asyncdispatch.q b/di/asyncdispatch/asyncdispatch.q new file mode 100644 index 00000000..4f9f3dd7 --- /dev/null +++ b/di/asyncdispatch/asyncdispatch.q @@ -0,0 +1,327 @@ +// di.asyncdispatch - async scatter-gather query coordinator +// queues queries, dispatches to available backends, collects results per server, +// applies a join function, and replies to the client +// routing (which servers satisfy a query) is di.serverselect's responsibility +// the log dependency is required - init errors immediately if absent or malformed +// log functions are binary {[c;m]} where c is a symbol context and m is a string + +// ============================================================ +// module state and defaults +// ============================================================ + +// error prefix prepended to all error strings returned to clients +errorprefix:"error: "; + +// how long completed queries are kept in queryqueue before being purged +querykeeptime:0D00:30; + +// how long disconnected servers are kept in the servers table before being removed +clearinactivetime:0D01:00; + +// whether synchronous calls via -30! are permitted +synccallsallowed:0b; + +// injectable clock - replaced in tests to control time without sleeping +cp:{.z.p}; + +// symbols backend servers call back via - stored as symbols so names survive IPC serialisation +resultcallback:`addserverresult; +errorcallback:`addservererror; + +// reply formatting - sync errors must be signalled with ' so the client receives a trapped error +formatresponse:{[status;sync;result]$[not[status]and sync;'result;result]}; + +// scheduling strategy - pick oldest FIFO-eligible query by default +getnextqueryid:{ + avail:exec distinct servertype from availableservers 1b; + // 0! is required - select from a keyed table stays keyed in kdb-x, and runnextquery needs queryid via first + runnable:0!select from .z.m.queryqueue where null returntime, not queryid in key .z.m.results, {all x in y}[;avail] each servertype; + 1 sublist select from runnable where time=min time + }; + +// server routing strategy - active and idle by default +availableservers:{[excludeinuse] + $[excludeinuse; + select from servers where active, not inuse; + select from servers where active] + }; + +// ============================================================ +// module tables +// ============================================================ + +// registered backend servers +servers:([handle:`u#`int$()] servertype:`symbol$(); inuse:`boolean$(); active:`boolean$(); disconnecttime:`timestamp$()); + +// pending and in-flight client queries +queryqueue:([queryid:`u#`long$()] time:`timestamp$(); clienth:`int$(); query:(); servertype:(); join:(); postback:(); timeout:`timespan$(); returntime:`timestamp$(); error:`boolean$(); sync:`boolean$(); local:`boolean$()); + +// connected client tracking +clients:([] time:`timestamp$(); clienth:`int$(); user:`symbol$(); ip:`int$(); host:`symbol$()); + +// per-query result accumulator: queryid -> (clienth; servertype!(handle;result;done)) +results:()!(); + +// auto-incrementing query id counter +queryid:0; + +// ============================================================ +// internal helpers +// ============================================================ + +sendclientreply:{[qid;result;status] + // deliver result or error to the client, handling sync vs async send and postback wrapping + // local path invokes value tosend directly - formatresponse is not applied (it is a pass-through + // for async by default; consumers that override setformatresponse should not use local invocation) + qd:queryqueue[qid]; + if[qd`error;:()]; + tosend:$[()~qd`postback;result;qd[`postback],enlist[qd`query],enlist result]; + $[qd`sync; + @[-30!;(qd`clienth;not status;$[status;formatresponse[1b;1b;result];result]);{}]; + $[qd`local; + @[value;tosend;{.z.m.logerr[`asyncdispatch;"local postback failed: ",x]}]; + @[neg qd`clienth;formatresponse[status;0b;tosend];()]]]; + }; + +finishquery:{[qid;err] + // remove query from the live results accumulator and stamp its completion time + .z.m.results:(qid,())_results; + update error:err,returntime:.z.m.cp[] from .z.M.queryqueue where queryid in qid; + }; + +serverexecute:{[rescb;errcb;qid;query] + // runs on the backend - traps errors so a crash posts an error reply rather than dropping the result. + // the result/error callback symbols are passed in as parameters (baked by sendquerytoserver on the + // dispatching side) rather than read as free variables here: read as free vars they would resolve in + // the BACKEND's namespace, forcing every caller to first push the callback vars onto each backend. + // baking them in keeps serverexecute fully self-contained, so backends need no cooperating code. + res:@[{(0b;value x)};query;{(1b;"server ",(string .z.h),":",(string system"p"),": ",x)}]; + @[neg .z.w;$[res 0;(errcb;qid;res 1);(rescb;qid;res 1)]; + {@[neg .z.w;(x;y;"failed to return result: ",z);()]}[errcb;qid]]; + }; + +sendquerytoserver:{[qid;query;handles] + // fan the query out to all required handles and mark them in-use atomically. + // project the configured callback symbols into serverexecute so they ship to the backend as baked + // literals - no backend-side variable lookup required. + (neg handles,:())@\:(serverexecute[.z.m.resultcallback;.z.m.errorcallback];qid;query); + update inuse:1b from .z.M.servers where handle in handles; + }; + +runnextquery:{[] + // pick the next dispatchable query and fan out to one idle server per required servertype + // called after any state change that may unblock work + if[0=count torun:getnextqueryid[];:()]; + torun:first torun; + avail:exec first handle by servertype from availableservers 1b; + types:torun`servertype; + handles:avail types; + qid:torun`queryid; + slots:types!count[types]#enlist(0Ni;(::);0b); + slots[types;0]:handles; + // indexed assignment on bare results propagates through to .z.m in kdb-x (empirically verified) + results[qid]:(torun`clienth;slots); + sendquerytoserver[qid;torun`query;handles]; + }; + +addqueryto:{[query;servertype;join;postback;timeout;sync;replyto;local] + // enqueue a query with an explicit reply target - used by execqueryto for local in-process routing + .z.M.queryqueue upsert (queryid;.z.m.cp[];replyto;query;servertype;join;{$[11h=type x;enlist x;x]}postback;timeout;0Np;0b;sync;local); + .z.m.queryid:queryid+1; + }; + +addquery:{[query;servertype;join;postback;timeout;sync] + // enqueue a query without dispatching - caller must call runnextquery[] to trigger dispatch + addqueryto[query;servertype;join;postback;timeout;sync;.z.w;0b]; + }; + +removequeries:{[age] + // prevent queryqueue growing unboundedly - purge completed queries older than age + delete from .z.M.queryqueue where not null returntime, .z.m.cp[]>returntime+age; + }; + +removeinactive:{[age] + // prune stale disconnected-server rows to stop the servers table growing forever + delete from .z.M.servers where not active, .z.m.cp[]>disconnecttime+age; + }; + +removeclients:{[age] + // prune stale client audit rows to stop the clients table growing forever + // clients are recorded on every connect by addclientdetails and never removed otherwise + delete from .z.M.clients where .z.m.cp[]>time+age; + }; + +checktimeout:{[] + // periodic scan to error queries that have waited beyond their timeout + qids:exec queryid from .z.m.queryqueue where not timeout=0Wn, null returntime, .z.m.cp[]>time+timeout; + if[count qids; + .z.m.logwarn[`asyncdispatch;"queries timed out: ",", " sv string qids]; + sendclientreply[;errorprefix,"query timed out";0b] each qids; + finishquery[qids;1b]]; + }; + +// ============================================================ +// public api +// ============================================================ + +setcp:{[f] + // replace the clock function - used in tests to control time without sleeping + .z.m.cp:f; + }; + +setformatresponse:{[f] + // override reply formatting - e.g. to wrap results in a standard envelope + .z.m.formatresponse:f; + }; + +setcallbacks:{[resfn;errfn] + // update callback symbols when module is mounted under a non-default namespace + .z.m.resultcallback:resfn; + .z.m.errorcallback:errfn; + }; + +setavailableservers:{[f] + // swap in a custom routing strategy without forking core dispatch + .z.m.availableservers:f; + }; + +setgetnextqueryid:{[f] + // inject a priority or custom scheduling strategy + .z.m.getnextqueryid:f; + }; + +addserver:{[h;st] + // register a backend handle and servertype so it becomes eligible for dispatch. + // this is the default (built-in) server source; to dispatch against di.serverselect's view instead, + // inject it via setavailableservers - no registration and no di.serverselect dependency required + .z.m.loginfo[`asyncdispatch;"server registered: ",string[st]," handle ",string h]; + .z.M.servers upsert (h;st;0b;1b;0Np); + }; + +removeserverhandle:{[serverh] + // on backend disconnect, error in-flight queries using that handle and queued queries + // that can no longer be satisfied + if[null st:first exec servertype from .z.m.servers where handle=serverh;:()]; + err:errorprefix,"backend ",string[st]," server disconnected"; + .z.m.logwarn[`asyncdispatch;"backend disconnected: ",string st]; + // in-flight: queries where this handle was assigned to a slot + qids:where {[h;qid]h in value[.z.m.results[qid;1]][;0]}[serverh] each key .z.m.results; + sendclientreply[;err," during query";0b] each qids; + finishquery[qids;1b]; + // queued: queries that can no longer be satisfied by remaining active servers + activetypes:exec distinct servertype from .z.m.servers where active, handle<>serverh; + qids2:exec queryid from .z.m.queryqueue where null returntime, not queryid in key .z.m.results, + not {all x in y}[;activetypes] each servertype; + sendclientreply[;err,", query cannot be satisfied";0b] each qids2; + finishquery[qids2;1b]; + update active:0b,disconnecttime:.z.m.cp[] from .z.M.servers where handle=serverh; + runnextquery[]; + }; + +addclientdetails:{[h] + // record client identity on connect for audit and orphan-query cleanup on disconnect + .z.m.loginfo[`asyncdispatch;"client connected: handle ",string h]; + .z.M.clients insert (.z.m.cp[];h;.z.u;.z.a;.z.h); + }; + +removeclienthandle:{[h] + // on client disconnect, mark their pending queries errored so result slots are not leaked + // free any servers in-flight for this client before removing result slots, then re-dispatch + // local queries store clienth:0Ni and are not matched here - the in-process caller owns cleanup for its own requests + .z.m.loginfo[`asyncdispatch;"client disconnected: handle ",string h]; + inflightqids:(exec queryid from .z.m.queryqueue where clienth=h, null returntime) inter key .z.m.results; + if[count inflightqids; + inflighthandles:distinct raze {value[.z.m.results[x;1]][;0]} each inflightqids; + update inuse:0b from .z.M.servers where handle in inflighthandles]; + update error:1b,returntime:.z.m.cp[] from .z.M.queryqueue where clienth=h, null returntime; + .z.m.results:(exec queryid from .z.m.queryqueue where clienth=h)_results; + runnextquery[]; + }; + +addserverresult:{[qid;data] + // fill one result slot - once all slots for a query are filled, run the join and reply + // bare indexed assignment on results propagates through to .z.m in kdb-x (empirically verified) + if[not qid in key results;:()]; + slots:results[qid;1]; + // map the responding handle to its servertype from THIS query's own dispatch record, not a server + // registry - so any server source (built-in or an injected di.serverselect view) works unchanged + st:first where .z.w=slots[;0]; + slots[st]:(.z.w;data;1b); + results[qid]:(results[qid;0];slots); + update inuse:0b from .z.M.servers where handle in .z.w; + runnextquery[]; + if[not qid in key results;:()]; + vals:value results[qid;1]; + if[not all vals[;2];:()]; + qd:queryqueue[qid]; + res:@[{(0b;x y)}[qd`join];vals[;1];{(1b;.z.m.errorprefix,"join failed: ",x)}]; + if[res 0;.z.m.logerr[`asyncdispatch;"join failed for query ",string qid,": ",last res]]; + sendclientreply[qid;last res;not res 0]; + finishquery[qid;res 0]; + }; + +addservererror:{[qid;err] + // short-circuit a query on backend failure - free the server and notify the client + .z.m.logerr[`asyncdispatch;"backend error for query ",string[qid],": ",err]; + sendclientreply[qid;errorprefix,err;0b]; + update inuse:0b from .z.M.servers where handle in .z.w; + runnextquery[]; + finishquery[qid;1b]; + }; + +execquery:{[query;servertype;join;postback;timeout;sync] + // public entry point - validate sync constraints then enqueue and kick dispatch + if[sync; + if[not ()~postback;.z.m.logwarn[`asyncdispatch;"execquery: postback ignored for sync call"]]; + if[not synccallsallowed;'"syncexec: synchronous calls are not allowed"]; + if[not @[{-30!x;1b};(::);0b];'"syncexec: deferred response not supported on this connection"]; + .[{[q;s;j;t]addquery[q;s;j;();t;1b];runnextquery[]};(query;servertype;join;timeout);{-30!(.z.w;1b;x)}]; + :()]; + addquery[query;servertype;join;postback;timeout;0b]; + runnextquery[]; + }; + +execqueryto:{[replyto;query;servertype;join;postback;timeout;sync] + // in-process variant of execquery - replyto is 0Ni for local invocation via value + // postback must be non-empty when replyto is 0Ni - there is no handle to send a bare result to + // sync is not supported for local invocation + // mount-qualified postback symbols required for local invocation e.g. `da.shardresult not `shardresult + if[0Ni~replyto; + if[()~postback;'"di.asyncdispatch: local invocation requires a non-empty postback"]; + if[sync;'"di.asyncdispatch: local invocation does not support sync mode"]]; + local:0Ni~replyto; + addqueryto[query;servertype;join;postback;timeout;sync;replyto;local]; + runnextquery[]; + }; + +init:{[deps] + // initialise the asyncdispatch module - validate deps and apply config overrides + // deps: dict containing `log (required) plus optional config keys: + // `log - required: `info`warn`error!({[c;m]};{[c;m]};{[c;m]}) binary loggers + // `errorprefix - optional: string prefix for client error messages. default: "error: " + // `querykeeptime - optional: timespan to keep completed queries. default: 0D00:30 + // `clearinactivetime - optional: timespan to keep disconnected servers. default: 0D01:00 + // `synccallsallowed - optional: boolean, whether sync calls are permitted. default: 0b + // housekeeping (checktimeout; removequeries; removeinactive; removeclients) is the caller's + // responsibility - wire them into your timer after init; the exported defaults for age params are + // querykeeptime and clearinactivetime + // examples: + // ad.init[enlist[`log]!enlist logdep] + // ad.init[`log`querykeeptime!(logdep;0D01:00)] + if[99h<>type deps; + '"di.asyncdispatch: deps must be a dict with `log key"]; + if[not `log in key deps; + '"di.asyncdispatch: log dependency is required; pass `info`warn`error!(infofn;warnfn;errfn) keyed on `log"]; + if[99h<>type deps`log; + '"di.asyncdispatch: log value must be a dict; pass `info`warn`error functions"]; + if[not all `info`warn`error in key deps`log; + '"di.asyncdispatch: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + .z.m.loginfo:(deps`log)`info; + .z.m.logwarn:(deps`log)`warn; + .z.m.logerr:(deps`log)`error; + if[`errorprefix in key deps; .z.m.errorprefix:deps`errorprefix]; + if[`querykeeptime in key deps; .z.m.querykeeptime:deps`querykeeptime]; + if[`clearinactivetime in key deps; .z.m.clearinactivetime:deps`clearinactivetime]; + if[`synccallsallowed in key deps; .z.m.synccallsallowed:deps`synccallsallowed]; + .z.m.loginfo[`asyncdispatch;"di.asyncdispatch initialised"]; + }; diff --git a/di/asyncdispatch/init.q b/di/asyncdispatch/init.q new file mode 100644 index 00000000..3a28372f --- /dev/null +++ b/di/asyncdispatch/init.q @@ -0,0 +1,16 @@ +// asyncdispatch module - async scatter-gather query coordinator for multi-backend kdb+ gateway processes +\l ::asyncdispatch.q + +// module version, read from the on-disk VERSION file (the module-local `:::` path convention). +// di.dataaccess's and di.proc.gateway's deps.toml both declare di.asyncdispatch, so +// di.torq.depcheck needs the file (pre-load walk) and this export (post-load audit). +version:first read0`:::VERSION + +export:([ + setformatresponse;setcallbacks;setavailableservers;setgetnextqueryid; + addserver;removeserverhandle; + addclientdetails;removeclienthandle; + addserverresult;addservererror; + execquery;execqueryto; + checktimeout;removequeries;removeinactive;removeclients; + init;version]) diff --git a/di/asyncdispatch/test.csv b/di/asyncdispatch/test.csv new file mode 100644 index 00000000..2ea47b06 --- /dev/null +++ b/di/asyncdispatch/test.csv @@ -0,0 +1,187 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,p:first {x where {10h=type @[hopen;`$raze("::";string x);{x}]} each x}[19500+til 100],1,,find first free port in range 19500-19599 +before,0,0,q,p2:first {x where {10h=type @[hopen;`$raze("::";string x);{x}]} each x}[19600+til 100],1,,find second free port in range 19600-19699 +before,0,0,q,system raze("q -p ";string p;" -q &"),1,,start first backend process on free port +before,0,0,q,system raze("q -p ";string p2;" -q &"),1,,start second backend process on free port +before,0,0,q,system"sleep 1",1,,wait for both backends to initialise +before,0,0,q,ad:use`di.asyncdispatch,1,,load module +before,0,0,q,srv:{.m.di.0asyncdispatch.servers},1,,live servers table +before,0,0,q,qq:{.m.di.0asyncdispatch.queryqueue},1,,live queryqueue table +before,0,0,q,cl:{.m.di.0asyncdispatch.clients},1,,live clients table +before,0,0,q,res:{.m.di.0asyncdispatch.results},1,,live results dict +before,0,0,q,mocklog:`info`warn`error!3#enlist{[c;m]},1,,mock log dep - binary {[c;m]} no-op +before,0,0,q,ad.init[enlist[`log]!enlist mocklog],1,,initialise with mock logger +before,0,0,q,ad.setcallbacks[`.m.di.0asyncdispatch.addserverresult;`.m.di.0asyncdispatch.addservererror],1,,configure result/error callbacks once on the dispatcher; serverexecute now bakes these into the dispatched call so backends need no pushed callback vars +before,0,0,q,bh:hopen`$raze("::";string p),1,,open handle to backend +before,0,0,q,ad.addserver[bh;`mock],1,,register first backend as mock server +before,0,0,q,bh2:hopen`$raze("::";string p2),1,,open handle to second backend +before,0,0,q,ad.addserver[bh2;`scatter],1,,register second backend as scatter servertype + +/ Test 0: server registry +true,0,0,q,bh in exec handle from srv[] where active,1,,first backend server is active +true,0,0,q,bh2 in exec handle from srv[] where active,1,,second backend server is active +true,0,0,q,bh in exec handle from .m.di.0asyncdispatch.availableservers 1b,1,,first backend is available for dispatch +true,0,0,q,bh2 in exec handle from .m.di.0asyncdispatch.availableservers 1b,1,,second backend is available for dispatch + +/ Test 1: queueing and FIFO scheduling +run,0,0,q,.m.di.0asyncdispatch.addquery["2+2";enlist`mock;raze;();0Wn;0b],1,,queue a query for the mock servertype +true,0,0,q,1~count select from qq[] where query~\:"2+2",1,,query was added to the queue +true,0,0,q,1~count .m.di.0asyncdispatch.getnextqueryid[],1,,query is runnable - idle mock server available +true,0,0,q,(enlist`mock)~first exec servertype from .m.di.0asyncdispatch.getnextqueryid[],1,,getnextqueryid identifies the available servertype + +/ Test 2: full dispatch -> result -> join -> reply via real IPC round-trip +run,0,0,q,qid1:exec first queryid from qq[] where query~\:"2+2",1,,capture the queued query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch query to real backend process +run,0,0,q,bh"",1,,sync round-trip: flushes dispatch and waits for backend result callback before returning +true,0,0,q,0b~first exec error from qq[] where queryid=qid1,1,,query completed without error +true,0,0,q,not null first exec returntime from qq[] where queryid=qid1,1,,returntime is stamped +true,0,0,q,not qid1 in key res[],1,,result accumulator cleaned up after join + +/ Test 3: checktimeout +run,0,0,q,.m.di.0asyncdispatch.addquery["3+3";enlist`mock;raze;();0D00:00:00.000000001;0b],1,,queue with a near-zero timeout +run,0,0,q,qid2:exec first queryid from qq[] where query~\:"3+3",1,,capture the queued query id +run,0,0,q,ad.checktimeout[],1,,timeout sweep should catch the expired query +true,0,0,q,1b~first exec error from qq[] where queryid=qid2,1,,timed-out query is flagged as error +true,0,0,q,not null first exec returntime from qq[] where queryid=qid2,1,,timed-out query has returntime stamped + +/ Test 4: removequeries purges completed queries +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p+2D}],1,,fast-forward the clock by 2 days +run,0,0,q,ad.removequeries .m.di.0asyncdispatch.querykeeptime,1,,purge queries older than querykeeptime +true,0,0,q,0~count select from qq[] where queryid in (qid1;qid2),1,,both completed queries purged +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p}],1,,restore the real clock + +/ Test 5: removeserverhandle errors queued queries when the only server disconnects +run,0,0,q,ad.addserver[1i;`mock2],1,,register a second mock server (fake handle - query is errored before dispatch) +run,0,0,q,.m.di.0asyncdispatch.addquery["4+4";enlist`mock2;raze;();0Wn;0b],1,,queue a query that can only run on mock2 +run,0,0,q,qid3:exec first queryid from qq[] where query~\:"4+4",1,,capture the queued query id +run,0,0,q,ad.removeserverhandle[1i],1,,disconnect the only server able to run the query +true,0,0,q,1b~first exec error from qq[] where queryid=qid3,1,,query errored as no server can satisfy it +true,0,0,q,0b~first exec active from srv[] where handle=1i,1,,disconnected server marked inactive + +/ Test 6: removeinactive purges inactive server records +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p+2D}],1,,fast-forward clock past clearinactivetime +run,0,0,q,ad.removeinactive .m.di.0asyncdispatch.clearinactivetime,1,,purge inactive servers +true,0,0,q,0~count select from srv[] where handle=1i,1,,inactive server record removed +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p}],1,,restore real clock + +/ Test 7: client tracking +run,0,0,q,ad.addclientdetails[2i],1,,record a connected client +true,0,0,q,1~count select from cl[] where clienth=2i,1,,client connection is tracked +run,0,0,q,ad.removeclienthandle[2i],1,,disconnect the client +true,0,0,q,0~count select from qq[] where (clienth=2i)&null returntime,1,,client unfinished queries cleared + +/ Test 8: pluggable hooks +run,0,0,q,ad.setformatresponse[{[status;sync;result]result}],1,,override formatresponse to pass result through +true,0,0,q,5~.m.di.0asyncdispatch.formatresponse[1b;0b;5],1,,overridden formatresponse is used +run,0,0,q,ad.setgetnextqueryid[{()}],1,,override scheduler to never pick a query +true,0,0,q,0~count .m.di.0asyncdispatch.getnextqueryid[],1,,overridden scheduler is used +run,0,0,q,ad.setcallbacks[`myresult;`myerror],1,,override callback symbols +true,0,0,q,(`myresult;`myerror)~(.m.di.0asyncdispatch.resultcallback;.m.di.0asyncdispatch.errorcallback),1,,callback symbols updated + +/ Test 9: removeclienthandle frees in-flight servers on client disconnect +run,0,0,q,ad.addserver[99i;`inflight],1,,register fake server for in-flight test +run,0,0,q,update inuse:1b from .m.di.0asyncdispatch.servers where handle=99i,1,,manually mark server in-use to simulate dispatched query +run,0,0,q,ad.addclientdetails[5i],1,,add fake client +run,0,0,q,.m.di.0asyncdispatch.addquery["5+5";enlist`inflight;raze;();0Wn;0b],1,,queue query for fake server +run,0,0,q,qid4:exec first queryid from qq[] where query~\:"5+5",1,,capture query id +run,0,0,q,.m.di.0asyncdispatch.results[qid4]:(5i;enlist[`inflight]!enlist(99i;(::);0b)),1,,inject in-flight slot to simulate dispatched-but-pending query +run,0,0,q,ad.removeclienthandle[5i],1,,disconnect client mid-flight +true,0,0,q,0b~first exec inuse from srv[] where handle=99i,1,,in-flight server freed on client disconnect +run,0,0,q,ad.removeserverhandle[99i],1,,clean up fake server + +/ Test 10: addservererror - real backend error path via IPC callback +run,0,0,q,ad.setcallbacks[`.m.di.0asyncdispatch.addserverresult;`.m.di.0asyncdispatch.addservererror],1,,restore callbacks overridden in test 8 +run,0,0,q,ad.setgetnextqueryid[{r:0!select from .m.di.0asyncdispatch.queryqueue where null returntime;1 sublist select from r where not queryid in key .m.di.0asyncdispatch.results}],1,,restore scheduler overridden in test 8 +run,0,0,q,.m.di.0asyncdispatch.addquery["'errortest";enlist`mock;raze;();0Wn;0b],1,,queue a query that will signal an error on the backend +run,0,0,q,qid5:exec first queryid from qq[] where query~\:"'errortest",1,,capture the queued query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch query to backend +run,0,0,q,bh"",1,,sync round-trip: ensures backend has processed and sent error callback +true,0,0,q,1b~first exec error from qq[] where queryid=qid5,1,,backend error callback flagged query as error +true,0,0,q,not null first exec returntime from qq[] where queryid=qid5,1,,returntime stamped on backend error + +/ Test 11: postback wrapping - non-empty postback produces (postback;query;result) tuple +run,0,0,q,captured::(),1,,global to capture what formatresponse receives +run,0,0,q,ad.setformatresponse[{[s;sync;r]captured::r;$[not[s]and sync;'r;r]}],1,,intercept formatresponse to verify tosend construction +run,0,0,q,.m.di.0asyncdispatch.addquery["7+7";enlist`mock;raze;enlist(::);0Wn;0b],1,,queue query with non-empty postback +run,0,0,q,qid6:exec first queryid from qq[] where query~\:"7+7",1,,capture query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch +run,0,0,q,bh"",1,,sync flush +true,0,0,q,0b~first exec error from qq[] where queryid=qid6,1,,postback query completed without error +true,0,0,q,(::;"7+7";enlist 14)~captured,1,,formatresponse received (postback;query;result) tuple +run,0,0,q,ad.setformatresponse[{[status;sync;result]$[not[status]and sync;'result;result]}],1,,restore default formatresponse + +/ Test 12: multi-servertype scatter-gather - two backends dispatched in parallel results joined +run,0,0,q,ad.setformatresponse[{[s;sync;r]captured::r;$[not[s]and sync;'r;r]}],1,,intercept formatresponse to capture joined result +run,0,0,q,.m.di.0asyncdispatch.addquery["1+1";`mock`scatter;{sum x};();0Wn;0b],1,,queue scatter-gather query requiring both servertypes +run,0,0,q,qid7:exec first queryid from qq[] where query~\:"1+1",1,,capture query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch to both backends in parallel +run,0,0,q,bh"",1,,sync flush first backend +run,0,0,q,bh2"",1,,sync flush second backend +true,0,0,q,0b~first exec error from qq[] where queryid=qid7,1,,scatter-gather completed without error +true,0,0,q,4~captured,1,,joined result is sum of both backend results (1+1=2 from each; sum 2 2 = 4) +run,0,0,q,ad.setformatresponse[{[status;sync;result]$[not[status]and sync;'result;result]}],1,,restore default formatresponse + +/ Test 13: execqueryto local path - successful result delivered in-process +run,0,0,q,ad.setcallbacks[`.m.di.0asyncdispatch.addserverresult;`.m.di.0asyncdispatch.addservererror],1,,restore callbacks +run,0,0,q,ad.setgetnextqueryid[{r:0!select from .m.di.0asyncdispatch.queryqueue where null returntime;1 sublist select from r where not queryid in key .m.di.0asyncdispatch.results}],1,,restore scheduler +run,0,0,q,.test.localcap:(::),1,,reset local capture +run,0,0,q,.test.localfn:{[reqid;qry;res] .test.localcap:(reqid;qry;res)},1,,define local capturing callback in root namespace +run,0,0,q,ad.execqueryto[0Ni;"2+2";enlist`mock;{sum x};(.test.localfn;`req1);0Wn;0b],1,,dispatch via local path with postback (sum collapses single-element result to scalar) +run,0,0,q,bh"",1,,sync flush - wait for backend result callback +true,0,0,q,(`req1;"2+2";4)~.test.localcap,1,,postback invoked in-process with (reqid;query;result) + +/ Test 14: execqueryto local path - backend error delivered in-process via postback +run,0,0,q,.test.localcap:(::),1,,reset local capture +run,0,0,q,ad.execqueryto[0Ni;"'errortest";enlist`mock;raze;(.test.localfn;`req2);0Wn;0b],1,,dispatch erroring query via local path +run,0,0,q,bh"",1,,sync flush - wait for backend error callback +true,0,0,q,`req2~.test.localcap[0],1,,reqid correct +true,0,0,q,.test.localcap[2] like "error:*",1,,error string delivered as result via postback + +/ Test 15: execqueryto local path - timeout delivered in-process via postback +run,0,0,q,.test.localcap:(::),1,,reset local capture +run,0,0,q,ad.execqueryto[0Ni;"3+3";enlist`mock;raze;(.test.localfn;`req3);0D00:00:00.000000001;0b],1,,dispatch with near-zero timeout +run,0,0,q,ad.checktimeout[],1,,trigger timeout sweep +true,0,0,q,`req3~.test.localcap[0],1,,reqid correct +true,0,0,q,.test.localcap[2] like "error:*",1,,timeout error delivered in-process via postback + +/ Test 16: removeclients purges stale client audit rows +run,0,0,q,ad.addclientdetails[7i],1,,record a client for the cleanup test +true,0,0,q,1~count select from cl[] where clienth=7i,1,,client audit row exists +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p+2D}],1,,fast-forward clock two days past the audit age +run,0,0,q,ad.removeclients[0D00:01],1,,purge client rows older than one minute +true,0,0,q,0~count select from cl[] where clienth=7i,1,,client audit row purged +run,0,0,q,.m.di.0asyncdispatch.setcp[{.z.p}],1,,restore the real clock + +/ Test 17: join-failure path - join function throws, client receives error and query is finished +/ dispatched to the scatter backend (bh2): the mock backend (bh) is left inuse by the in-flight timeout in test 15 +run,0,0,q,.m.di.0asyncdispatch.addquery["2+2";enlist`scatter;{'"joinboom"};();0Wn;0b],1,,queue a query whose join function throws +run,0,0,q,qid8:exec first queryid from qq[] where join~\:{'"joinboom"},1,,capture the query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch to the scatter backend +run,0,0,q,bh2"",1,,sync flush - wait for the result callback and join attempt +true,0,0,q,1b~first exec error from qq[] where queryid=qid8,1,,join failure correctly flagged as error +true,0,0,q,not null first exec returntime from qq[] where queryid=qid8,1,,returntime stamped after join failure + +/ Test 18: execqueryto with a non-null explicit replyto stores it as clienth with local=0b +run,0,0,q,ad.execqueryto[99i;"1+1";enlist`scatter;{sum x};();0Wn;0b],1,,dispatch with explicit replyto handle 99i +run,0,0,q,qid9:exec first queryid from qq[] where (clienth=99i)&query~\:"1+1",1,,capture the query id +true,0,0,q,99i~first exec clienth from qq[] where queryid=qid9,1,,replyto stored as clienth +true,0,0,q,0b~first exec local from qq[] where queryid=qid9,1,,local flag is 0b for a non-null replyto +run,0,0,q,bh2"",1,,sync flush - completes the backend round-trip (reply to fake 99i fails silently) + +/ Test 19: pluggable server source - dispatch against an injected source whose servertype is not in the +/ internal registry; result routing uses the query's dispatch record so no internal registration is needed +run,0,0,q,savedavail:.m.di.0asyncdispatch.availableservers,1,,save the default (internal-registry) server source +run,0,0,q,ad.setavailableservers[{[eu]([]handle:enlist bh;servertype:enlist`ext)}],1,,inject a source presenting bh under servertype ext (bh is registered as mock) +run,0,0,q,.m.di.0asyncdispatch.addquery["6*7";enlist`ext;raze;();0Wn;0b],1,,queue a query for the external-only servertype +run,0,0,q,qidx:exec first queryid from qq[] where query~\:"6*7",1,,capture the query id +run,0,0,q,.m.di.0asyncdispatch.runnextquery[],1,,dispatch to bh via the injected source +run,0,0,q,bh"",1,,sync flush - wait for the backend result callback +true,0,0,q,0b~first exec error from qq[] where queryid=qidx,1,,query completed without error via the injected source +true,0,0,q,not null first exec returntime from qq[] where queryid=qidx,1,,result routed via the dispatch record (servertype ext) not the servers table (mock) +run,0,0,q,ad.setavailableservers[savedavail],1,,restore the default internal-registry source + +/ Teardown +run,0,0,q,neg[bh](exit;0);neg[bh](::),1,,send exit to first backend process and flush +run,0,0,q,hclose bh,1,,close first backend handle +run,0,0,q,neg[bh2](exit;0);neg[bh2](::),1,,send exit to second backend process and flush +run,0,0,q,hclose bh2,1,,close second backend handle diff --git a/di/compression/compression.md b/di/compression/compression.md index 227beb0d..65165809 100644 --- a/di/compression/compression.md +++ b/di/compression/compression.md @@ -24,7 +24,7 @@ Passed as a dictionary to `init`. The `log` dependency is required — `init` th | Key | Required | Type | Description | |---|---|---|---| -| `` `log `` | yes | dict | Logger with keys `` `info`warn`error ``, each `{[c;m]}`. See `di.log` for a default implementation. | +| `` `log `` | yes | dict | Logger with keys `` `info`warn`error ``, each `{[c;m]}`. See `di.util.log` for a default implementation. | --- diff --git a/di/compression/compression.q b/di/compression/compression.q index a655d049..848b3a68 100644 --- a/di/compression/compression.q +++ b/di/compression/compression.q @@ -197,7 +197,7 @@ init:{[deps] / cmp.init[enlist[`log]!enlist logdep] logdict:$[99h=type deps;$[(`log in key deps) and not (::)~deps`log;deps`log;()!()];()!()]; if[not count logdict; - '"di.compression: log dependency is required; pass `info`warn`error functions - see di.log or refer to confluence documentation"; + '"di.compression: log dependency is required; pass `info`warn`error functions - see di.util.log or refer to confluence documentation"; ]; .z.m.loginfo:logdict`info; .z.m.logwarn:logdict`warn; diff --git a/di/dataaccess/VERSION b/di/dataaccess/VERSION new file mode 100644 index 00000000..0d91a54c --- /dev/null +++ b/di/dataaccess/VERSION @@ -0,0 +1 @@ +0.3.0 diff --git a/di/dataaccess/dataaccess.md b/di/dataaccess/dataaccess.md new file mode 100644 index 00000000..5294aba0 --- /dev/null +++ b/di/dataaccess/dataaccess.md @@ -0,0 +1,90 @@ +# di.dataaccess + +The **query-normalisation / `getdata` layer** over the gateway. It solves the classic +kdb+tick problem that the **RDB has no `date` column** (it's in-memory; `date` is only a +*virtual* partition column on the HDB), so a query like `select … by date from trade` works on +the HDB but breaks on the RDB. `getdata` takes a **structured, time-ranged** request, routes it +across the time-partitioned backends, **builds a valid per-backend query** (normalising `date`), +scatters the shards, and **map-reduces** the results back to the client. + +Modelled on kdbx-modules `feature-dataaccess` (early WIP) but rebuilt — see the header of +`dataaccess.q` for the three substantive differences (functional-qSQL building vs string +rewriting; `execqueryto` local dispatch vs the branch's broken `.z.w` reply path; real +map-reduce vs a bare `raze`). + +## Dependencies + +- **Hard** (`use`): `di.asyncdispatch` (dispatch), `di.serverselect` (which servertypes are + live). Both are **shared** with di.proc.gateway (idempotent `use`), so getdata dispatches through + the gateway's already-registered servers and callbacks. +- **Injected** (`init` deps dict): `log`, `timer` (required) + optional `partitions`, + `timecolumn` (default `` `time ``), `partitioncolumn` (default `` `date ``), `cp`, + `requestkeeptime`, `resultcallback`. + +## `getdata[tablename; starttime; endtime; by; aggs]` + +- `tablename` — symbol. +- `starttime`/`endtime` — timestamps; the request's time range. +- `by` — grouping columns (symbol list; `` ` `` / `()` for none). `` `date `` is **normalised + per backend**: the HDB uses its native `date` column; the RDB derives `` `date$ ``. +- `aggs` — a `(outcol; aggfn; incol)` triple or list of them, e.g. + `` ((`cnt;`count;`i);(`vol;`sum;`size)) ``; `` ` ``/`()` for a plain row select. `aggfn` ∈ + `` `count`sum`min`max`avg`wavg`vwap ``. For `wavg`/`vwap` the `incol` is a + `(weight; value)` **pair**, e.g. `` (`vw;`vwap;`size`price) `` (= `size wavg price`). + +Deferred-sync from a client: `neg[gw](`.gw.getdata; `trade; st; et; `date`sym; (`cnt;`count;`i)); gw[]`. + +### How it normalises + map-reduces +1. **Route** (`getrouting`): clip `[starttime;endtime]` against the `partitions` coverage table + (one shard per reachable servertype, non-overlapping ranges). +2. **Build** (`buildshardquery`): a **functional** select `?[t;wc;b;a]` per shard — a `within` + time filter (plus a partition-column filter on the HDB so kdb prunes partitions), the + date-normalised `by`, and the **shard-level** aggregation (e.g. `count`). +3. **Scatter**: one `di.asyncdispatch.execqueryto[0Ni;…]` per shard (local mode → replies come + back to the root-published `.dataaccess.shardresult`, not the end client). +4. **Reduce** (`checkresults`): once all shards are in, unkey + `raze` them and re-group on the + by-keys applying each agg's **reduce** fn — so grouped aggregates recombine correctly instead of + double-counting. Aggregates that can't be recombined from their own shard value are split into + **components** (`aggspecs`): `avg` → per-shard `sum` + non-null `count`, recombined as + `(sum sums)%(sum counts)`; `wavg`/`vwap` → per-shard `sum(w*c)` + `sum(w)`, recombined as + `(sum nums)%(sum dens)`. `count`/`sum`/`min`/`max` are single-component (`sum`/`sum`/`min`/`max`). + +## Partition coverage + +```q +partitions:([] servertype:`rdb`hdb; coverfrom:(`timestamp$.z.d; -0Wp); coverto:(0Wp; -1+`timestamp$.z.d)) +``` +`coverfrom`/`coverto` are timestamps (`-0Wp`/`0Wp` for open ends); **keep them non-overlapping** +or a slice is double-counted. di.proc.gateway builds this from `.z.d` at init (rdb = today onward, +hdb = before today) and **refreshes it at rollover** by calling `setpartitions[parts]` from its EOD +`reloadend` handler — after the wdb has moved the just-ended day's partition into the hdb, `.z.d` +has advanced, so the rolled day now correctly routes to the hdb instead of the rdb (which dropped it). + +## `setpartitions[parts]` + +Swap the routing coverage table at runtime (same-shape table as above; columns validated). Published +as a module export; di.proc.gateway calls it at EOD `reloadend`. Call it yourself if your stack rolls +partitions on a schedule the gateway doesn't drive. + +## Scope / deferred + +- **In**: `count`/`sum`/`min`/`max`/`avg`/`wavg`/`vwap` (all map-reduce correctly across shards); + `` `date `` + plain by-columns; a single time-range filter; rollover refresh of `partitions` + (`setpartitions`, driven by the gateway at EOD). +- **Deferred**: arbitrary `where` filters and column projections; ordering / `sublist`; typed input + validation (TorQ's `checkinputs`); attribute-based routing. + +`avg` uses a non-null count denominator to match q's null-ignoring `avg`; `wavg`/`vwap` follow the +`sum(w*c)%sum(w)` definition (nulls drop consistently across numerator and denominator). + +## Testing + +`test.csv` (k4unit) covers the dependency contract + export surface + that init publishes its +local-postback entry points. The functional query-building, date normalisation and map-reduce +recombine are validated directly, and the full **client → getdata → per-backend normalised +shards → map-reduce** flow across a live rdb+hdb is proven in the TorqX-POC end-to-end. + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.dataaccess +``` diff --git a/di/dataaccess/dataaccess.q b/di/dataaccess/dataaccess.q new file mode 100644 index 00000000..5e2439f5 --- /dev/null +++ b/di/dataaccess/dataaccess.q @@ -0,0 +1,345 @@ +/ di.dataaccess - data access / query normalisation layer over the gateway. Accepts a +/ structured, time-ranged request, ROUTES it across time-partitioned backends (one shard per +/ reachable servertype, clipped to its coverage), BUILDS a per-backend FUNCTIONAL-qSQL query +/ (normalising the date column - native `date` on the hdb, derived `date$time` on the rdb), +/ SCATTERS the shards via di.asyncdispatch, then GATHERS and MAP-REDUCES the results back to +/ the client. This is the "generic getdata that handles the rdb-has-no-date-column problem". +/ --- +/ MERGE of two implementations (see docs/reconciliation/dataaccess.md). The structure - routing, +/ scatter/gather/reduce, requests/shardresults bookkeeping, the postback/timeout/deferred-sync +/ request lifecycle - is kdbx-modules feature-dataaccess's, kept. On top of it: +/ (1) queries are also built FUNCTIONALLY (?[t;wc;b;a]) rather than only by string rewriting - +/ robust, and the seam for per-backend date normalisation; +/ (2) dispatch goes through di.asyncdispatch.execqueryto LOCAL mode (replyto 0Ni + a +/ root-published .dataaccess.shardresult postback) - the branch used execquery and hit the +/ ".z.w replies to the client, not to dataaccess" bug its own .md flagged as unfixable from +/ its side; execqueryto (added to asyncdispatch since) is that fix; +/ (3) real map-reduce (a shard-fn then a reduce-fn recombined on the by-keys, with a component +/ split for avg/wavg/vwap) rather than a bare user raze that double-counts grouped aggs. +/ Both entry points are kept and share the whole core: +/ getdata / getdatafull - typed, date-normalising, map-reducing +/ execquery - arbitrary query STRING, time-sharded, caller-supplied joinfn +/ --- +/ Hard deps (use): di.asyncdispatch (dispatch), di.serverselect (which servertypes are live) - +/ SHARED (idempotent use) with di.proc.gateway, so it reuses the gateway's registered servers + +/ callbacks. Injected via init: log, timer (required) + optional config. +/ Scope: count/sum/min/max/avg + wavg/vwap aggs (avg & the weighted pair map-reduce correctly via a +/ component split - see aggspecs); `date` + plain by-columns; a single time-range filter. Coverage is +/ refreshed at EOD via setpartitions (the gateway calls it at reloadend). Deferred: arbitrary where +/ filters, ordering/sublist, typed input validation (TorQ checkinputs), attribute routing. + +asyncdispatch:use`di.asyncdispatch; +serverselect:use`di.serverselect; + +errorprefix:"error: "; + +/ default coverage: one hdb over all time; override via init `partitions +defaultpartitions:([]servertype:enlist`hdb;coverfrom:enlist -0Wp;coverto:enlist 0Wp); + +/ agg fn -> (COMPONENTS; REDUCEFN). The map-reduce split: an aggregate that can't be recombined +/ from its own shard-level value (avg, wavg/vwap) is decomposed into COMPONENTS that CAN - each a +/ hidden per-shard aggregate column - and a REDUCEFN that recombines those components (regrouped +/ on the by-keys) into the final value. count/sum/min/max are single-component (the output col +/ itself); avg = sum + non-null-count, recombined as (sum sums)%(sum counts); wavg/vwap = sum(w*c) +/ + sum(w), recombined as (sum nums)%(sum dens). All exprs are functional-qSQL parse trees, so a +/ bare column symbol is a column reference. +/ COMPONENTS : list of (suffix; shardbuilder[incol]->parsetree). suffix ` = the output col +/ itself (single-component, back-compatible); else the hidden col is __. +/ REDUCEFN : compnames -> parsetree combining the (already-grouped) component columns. +/ NB avg's denominator is sum(not null c) to match q's null-ignoring avg; count (the standalone +/ agg) still counts rows. wavg/vwap follow the sum(w*c)%sum(w) definition (nulls drop consistently). +compname:{[o;suffix] $[suffix~`;o;`$string[o],"__",string suffix]}; +aggspecs:()!(); +aggspecs[`count]:(enlist(`;{[c] (count;c)}); {[cn] (sum;cn 0)}); +aggspecs[`sum]: (enlist(`;{[c] (sum;c)}); {[cn] (sum;cn 0)}); +aggspecs[`min]: (enlist(`;{[c] (min;c)}); {[cn] (min;cn 0)}); +aggspecs[`max]: (enlist(`;{[c] (max;c)}); {[cn] (max;cn 0)}); +aggspecs[`avg]: (((`s;{[c] (sum;c)});(`n;{[c] (sum;(not;(null;c)))})); {[cn] ((%);(sum;cn 0);(sum;cn 1))}); +aggspecs[`wavg]: (((`n;{[c] (sum;(*;c 0;c 1))});(`d;{[c] (sum;c 0)})); {[cn] ((%);(sum;cn 0);(sum;cn 1))}); +aggspecs[`vwap]: aggspecs`wavg; + +/ one row per in-flight request. `mode selects how checkresults recombines the shard results: +/ `getdata - structured map-reduce over `by/`aggs (this module's typed entry point) +/ `execquery - apply the caller's `joinfn across the raw shard results (the string entry point) +/ so `by`aggs are meaningful only for `getdata and `joinfn only for `execquery; the rest of the +/ lifecycle (postback wrapping, timeout, deferred-sync reply, purge) is common to both. +requestschema:([requestid:`u#`long$()] + time:`timestamp$(); clienth:`int$(); remaining:`long$(); + mode:`symbol$(); by:(); aggs:(); joinfn:(); + postback:(); timeout:`timespan$(); + returntime:`timestamp$(); error:`boolean$(); sync:`boolean$()); + +/ --- internal helpers --- + +normlog:{[logdict] + / normalise an injected logger to a binary `info`warn`error!{[c;m]} dict (kx.log is monadic - + / wrap and fold the context in); an already-binary dict passes through unchanged + $[any `getlvl`sinks`fmts in key logdict; + `info`warn`error!{[fn;c;m] fn[string[c],": ",m]}[;;]'[logdict`info`warn`error]; + logdict] + }; + +raiseerror:{[ctx;msg] .z.m.log[`error][ctx;msg]; '"di.dataaccess: ",string[ctx],": ",msg}; +getopt:{[deps;k;dflt] $[k in key deps;deps k;dflt]}; + +/ --- routing (which servertypes + sub-ranges cover [starttime;endtime]) --- + +getrouting:{[starttime;endtime] + active:exec distinct servertype from (.z.m.serverselect`getservers)[`servertype;`;()!()]; + parts:select from .z.m.partitions where servertype in active; + shards:select servertype,rangestart:coverfrom|starttime,rangeend:coverto&endtime from parts; + select from shards where rangestart`. +byexpr:{[servertype;tc;pc;c] $[c=pc; $[servertype=`hdb; pc; ($;enlist`date;tc)]; c]}; + +buildshardquery:{[servertype;tab;by;aggd;rs;re;tc;pc] + / where: time within the shard range; on the hdb also constrain the partition column so kdb + / prunes partitions instead of scanning every date's time column + wc:enlist (within;tc;(rs;re)); + if[(servertype=`hdb) and not tc~pc; wc:wc,enlist (within;pc;(`date$rs;`date$re))]; + / no aggs -> plain row select (all cols), grouping ignored + if[0=count aggd; :(?;tab;wc;0b;())]; + b:$[0=count by;0b;(by)!byexpr[servertype;tc;pc] each by]; + / expand each output col into its shard COMPONENT columns (compname!shardexpr), merge across cols + a:(,/){[o;spec] cs:(aggspecs spec 0)0; (compname[o;]each cs[;0])!{[b;ic] b ic}[;spec 1]each cs[;1]}'[key aggd;value aggd]; + (?;tab;wc;b;a) + }; + +/ --- string query building (the execquery entry point) --- + +/ inject the shard's time range into a qSQL query STRING as a within filter on the time column, +/ appended as the last clause so it works whether or not the query already has a where. +/ String-based by design (from kdbx-modules feature-dataaccess, kept verbatim in behaviour): it +/ assumes a flat select string and is NOT robust to subqueries, fby, or the literal text "where" +/ inside a string constant. getdata's functional builder above has none of those limits - prefer +/ it where the query is structured; this exists for callers holding an arbitrary query string. +buildstringshardquery:{[query;rangestart;rangeend] + clause:(string .z.m.timecolumn)," within (",(string rangestart),";",(string rangeend),")"; + $[query like "*where*";query," , ",clause;query," where ",clause] + }; + +/ --- shard accumulation + reduce --- + +shardresult:{[reqid;query;result] + / asyncdispatch local postback: (reqid;query;result). Backend errors arrive as an + / errorprefix-prefixed STRING through this same postback - detect and short-circuit. + if[(10h=type result) and errorprefix~(count errorprefix) sublist result; + :sharderror[reqid;(count errorprefix) _ result]]; + if[not reqid in key .z.m.requests;:()]; + if[not null .z.m.requests[reqid;`returntime];:()]; + .z.m.shardresults[reqid],:enlist result; + n:.z.m.requests[reqid;`remaining]-1; + .z.m.requests:update remaining:n from .z.m.requests where requestid=reqid; + if[0=n;checkresults reqid]; + }; + +sharderror:{[reqid;err] + if[not reqid in key .z.m.requests;:()]; + if[not null .z.m.requests[reqid;`returntime];:()]; + .z.m.log[`error][`sharderror;"shard error for request ",string[reqid],": ",err]; + sendreply[reqid;errorprefix,err;0b]; + finishrequest[reqid;1b]; + }; + +checkresults:{[reqid] + / all shards in - recombine according to the request's mode, then reply. + / `getdata - plain (no agg): raze the shard tables. Aggregated: re-group the razed shards on + / the by-keys applying each agg's REDUCE fn (count/sum->sum, min->min, max->max). + / `execquery - apply the caller's joinfn across the raw shard results (kdbx branch behaviour). + req:.z.m.requests reqid; + res:$[req[`mode]~`execquery; + .[{(0b;x y)};(req`joinfn;.z.m.shardresults reqid);{(1b;errorprefix,"join failed: ",x)}]; + .[{[by;aggd;t] + (0b; $[0=count aggd; t; + ?[t; (); $[0=count by;0b;(by)!by]; + (key aggd)!{[o;spec] cs:(aggspecs spec 0)0; ((aggspecs spec 0)1) compname[o;]each cs[;0]}'[key aggd;value aggd]]])}; + / 0! - grouped shard results are keyed; unkey before razing + (req`by;req`aggs;raze 0!'.z.m.shardresults reqid); {(1b;errorprefix,"reduce failed: ",x)}]]; + if[res 0;.z.m.log[`error][`checkresults;"recombine failed for request ",string[reqid],": ",last res]]; + sendreply[reqid;last res;not res 0]; + finishrequest[reqid;res 0]; + }; + +sendreply:{[reqid;result;status] + req:.z.m.requests reqid; + if[req`error;:()]; + tosend:$[()~req`postback;result;req[`postback],enlist result]; + $[req`sync; @[-30!;(req`clienth;not status;result);{}]; @[neg req`clienth;tosend;()]]; + }; + +finishrequest:{[reqid;err] + .z.m.shardresults:(reqid,()) _ .z.m.shardresults; + .z.m.requests:update error:err,returntime:.z.m.cp[] from .z.m.requests where requestid=reqid; + }; + +submitshards:{[reqid;shards;timeout] + / one asyncdispatch call per shard, LOCAL mode (replyto 0Ni) so the reply comes back to + / .dataaccess.shardresult (root-published) not the end client. join=first: a shard is a single + / servertype, so asyncdispatch returns that one backend's result as-is for us to reduce. + / NB execqueryto (not execquery): execquery captures clienth:.z.w at call time, which in-process + / is the END CLIENT's handle, so the reply would bypass dataaccess entirely - the integration bug + / the kdbx branch documented but could not fix from its side. replyto 0Ni is the local-mode fix. + {[reqid;timeout;stype;q] + (.z.m.asyncdispatch`execqueryto)[0Ni; q; enlist stype; first; (.z.m.resultcallback;reqid); timeout; 0b] + }[reqid;timeout]'[shards`servertype; shards`shardquery]; + }; + +/ --- request lifecycle helpers (shared by both entry points) --- + +/ guard a deferred-sync request: sync must be permitted by config AND supported by this connection. +checksync:{[ctx;sync] + if[not sync;:()]; + if[not .z.m.synccallsallowed;raiseerror[ctx;"synchronous calls are not allowed"]]; + if[not @[{-30!x;1b};(::);0b];raiseerror[ctx;"deferred response not supported on this connection"]]; + }; + +/ nothing covers the requested range: reply empty, honouring postback wrapping and deferred sync, +/ and still burn a request id so ids stay monotonic. (kdbx branch behaviour - TorqX's getdata sent +/ a bare async empty and ignored postback/sync.) +replyempty:{[postback;sync;empty] + tosend:$[()~postback;empty;postback,enlist empty]; + $[sync;@[-30!;(.z.w;0b;empty);{}];@[neg .z.w;tosend;()]]; + .z.m.requestid:1+.z.m.requestid; + }; + +normpostback:{[postback] $[11h=abs type postback;(),postback;postback]}; + +/ build the one-row request table for an upsert. Deliberately an ENLISTED DICT rather than a bare +/ tuple: a row carrying more than one empty-list cell (e.g. an unused joinfn AND no postback) is +/ ambiguous to q - it cannot tell one row from a set of column vectors - and upsert throws 'type. +/ recombine: the mode-specific triple (by;aggs;joinfn) - passed as one argument because a q lambda +/ takes at most 8 parameters and the full row needs nine values ('params at load otherwise). +newrequest:{[reqid;nshards;mode;recombine;postback;timeout;sync] + enlist `requestid`time`clienth`remaining`mode`by`aggs`joinfn`postback`timeout`returntime`error`sync! + (reqid;.z.m.cp[];.z.w;nshards;mode;recombine 0;recombine 1;recombine 2;postback;timeout;0Np;0b;sync) + }; + +/ --- public API --- + +getdatafull:{[tablename;starttime;endtime;by;aggs;postback;timeout;sync] + / by: symbol list of grouping columns (`date normalised per backend); ` or () for none. + / aggs: a (out;fn;incol) triple or a list of them, e.g. ((`cnt;`count;`i);(`vol;`sum;`size)); + / ` or () for a plain row select. fn in `count`sum`min`max`avg`wavg`vwap. + / postback: () for a plain reply, else (fn;args...) prepended to the result before sending. + / timeout: per-shard dispatch timeout (0Wn for none). + / sync: 1b to answer the caller via a deferred (-30!) response; needs `synccallsallowed. + if[not `log in key .z.m;'"di.dataaccess: init must be called before getdata"]; + checksync[`getdata;sync]; + by:(),$[(::)~by;`;by]; by:by where not null by; + / -> list of (out;fn;incol) triples. A single triple is either a plain symbol triple (type 11h) + / or, when incol is a (weight;value) pair (wavg/vwap), a generic list whose first item is a symbol + / atom - distinguish from a list-of-triples (whose first item is itself a triple, not an atom). + aggs:$[(::)~aggs;(); + 11h=type aggs;enlist aggs; + (0h=type aggs)and -11h=type first aggs;enlist aggs; + aggs]; + aggs:aggs where 0 empty + qs:buildshardquery[;tablename;by;aggd;;;.z.m.timecolumn;.z.m.partitioncolumn]'[shards`servertype;shards`rangestart;shards`rangeend]; + shards:shards,'flip(enlist`shardquery)!enlist qs; + reqid:.z.m.requestid; + / upsert an ENLISTED DICT, not a bare tuple: with more than one empty-list cell (here joinfn and + / an absent postback) q cannot tell a single row from a set of column vectors and throws 'type. + .z.m.requests:.z.m.requests upsert newrequest[reqid;count shards;`getdata;(by;aggd;());postback;timeout;sync]; + .z.m.shardresults[reqid]:(); + submitshards[reqid;shards;timeout]; + .z.m.requestid:1+.z.m.requestid; + }; + +/ simple form: no postback, no timeout, async. Delegates to getdatafull - same pairing convention +/ as di.proc.gateway's asyncexec/asyncexecjpt, so existing 5-arg .gw.getdata callers are unaffected. +/ NB must be defined AFTER getdatafull: a module-local name is rewritten to the module namespace at +/ COMPILE time, so a forward reference here silently falls through to root and throws 'type on call. +getdata:{[tablename;starttime;endtime;by;aggs] + getdatafull[tablename;starttime;endtime;by;aggs;();0Wn;0b] + }; + +execquery:{[query;starttime;endtime;joinfn;postback;timeout;sync] + / STRING entry point (from kdbx-modules feature-dataaccess): route an arbitrary qSQL query string + / across the partition coverage, rewrite each shard's time filter into the string, scatter, then + / recombine with the caller's joinfn. Complements getdata: getdata is typed, date-normalising and + / map-reducing but only builds the query shapes it knows; execquery takes any query string but + / cannot normalise `date (the rdb has no date column) and leaves recombination to the caller. + / Distinct from di.proc.gateway's .gw.asyncexecjpt, which sends one query to chosen servertypes + / with no time-range routing at all - this shards a raw string across the time partitions. + if[not `log in key .z.m;'"di.dataaccess: init must be called before execquery"]; + checksync[`execquery;sync]; + postback:normpostback postback; + shards:getrouting[starttime;endtime]; + if[0=count shards; :replyempty[postback;sync;enlist[]]]; + qs:buildstringshardquery[query;;]'[shards`rangestart;shards`rangeend]; + shards:shards,'flip(enlist`shardquery)!enlist qs; + reqid:.z.m.requestid; + / by is `$() (an empty symbol VECTOR), not the ` atom: the by column is declared general, and the + / FIRST row inserted fixes its type - an atom would collapse it to a simple symbol column and the + / next getdata request (whose by IS a vector) would then fail the upsert with 'type. + .z.m.requests:.z.m.requests upsert newrequest[reqid;count shards;`execquery;(`$();()!();joinfn);postback;timeout;sync]; + .z.m.shardresults[reqid]:(); + submitshards[reqid;shards;timeout]; + .z.m.requestid:1+.z.m.requestid; + }; + +removerequests:{[age] + .z.m.requests:delete from .z.m.requests where not null returntime, .z.m.cp[]>returntime+age; + }; + +checkpartitions:{[t] + if[not all `servertype`coverfrom`coverto in cols t; + '"di.dataaccess: partitions table needs columns servertype, coverfrom, coverto"]; + }; + +/ swap the routing coverage table at runtime. The gateway calls this at EOD reloadend, after the +/ wdb has moved the just-ended day's partition into the hdb: "today" now belongs to the hdb and the +/ new day to the rdb, so the static-at-init coverage must be refreshed or post-EOD queries for the +/ rolled day would still route to the rdb (which has dropped it). Keep the ranges non-overlapping. +setpartitions:{[parts] + checkpartitions parts; + .z.m.partitions:parts; + .z.m.log[`info][`setpartitions;"partition coverage refreshed: ",(", " sv string exec servertype from parts)]; + }; + +init:{[deps] + if[99h<>type deps;'"di.dataaccess: deps must be a dict with `log and `timer keys"]; + if[not `log in key deps;'"di.dataaccess: log dependency is required"]; + if[99h<>type deps`log;'"di.dataaccess: log value must be a dict of `info`warn`error"]; + if[not all `info`warn`error in key deps`log;'"di.dataaccess: log dict needs `info`warn`error"]; + if[not `timer in key deps;'"di.dataaccess: timer dependency is required"]; + if[`partitions in key deps;checkpartitions deps`partitions]; + .z.m.log:normlog deps`log; + .z.m.timer:deps`timer; + .z.m.asyncdispatch:asyncdispatch; + .z.m.serverselect:serverselect; + .z.m.cp:getopt[deps;`cp;{.z.p}]; + .z.m.synccallsallowed:getopt[deps;`synccallsallowed;0b]; + .z.m.requestkeeptime:getopt[deps;`requestkeeptime;0D00:30]; + .z.m.resultcallback:getopt[deps;`resultcallback;`.dataaccess.shardresult]; + .z.m.partitions:getopt[deps;`partitions;defaultpartitions]; + .z.m.timecolumn:getopt[deps;`timecolumn;`time]; + .z.m.partitioncolumn:getopt[deps;`partitioncolumn;`date]; + .z.m.requests:requestschema; + .z.m.shardresults:()!(); + .z.m.requestid:0; + / publish the local-postback entry points at root so asyncdispatch's execqueryto can `value them + set[`.dataaccess.shardresult;shardresult]; + set[`.dataaccess.sharderror;sharderror]; + .z.m.log[`info][`init;"di.dataaccess initialised"]; + (.z.m.timer`addjob)[`dataaccesspurge;removerequests;enlist .z.m.requestkeeptime;1800;1h;()!()]; + }; diff --git a/di/dataaccess/deps.toml b/di/dataaccess/deps.toml new file mode 100644 index 00000000..584a73f2 --- /dev/null +++ b/di/dataaccess/deps.toml @@ -0,0 +1,4 @@ +# Peer modules di.dataaccess `use`s (see di/depcheck/depcheck.md). +[dependencies] +"di.asyncdispatch" = "0.1.0" +"di.serverselect" = "0.1.0" diff --git a/di/dataaccess/init.q b/di/dataaccess/init.q new file mode 100644 index 00000000..a73ec8ad --- /dev/null +++ b/di/dataaccess/init.q @@ -0,0 +1,12 @@ +/ di.dataaccess - data access / query normalisation layer over the gateway. +/ Two entry points over one shared routing + scatter/gather + request-lifecycle core: +/ getdata / getdatafull - typed, date-normalising, map-reducing (TorqX) +/ execquery - arbitrary query STRING, time-sharded, caller-supplied joinfn (kdbx) +/ See docs/reconciliation/dataaccess.md for the merge rationale. + +\l ::dataaccess.q + +version:first read0`:::VERSION + +export:([init;getdata;getdatafull;execquery;setpartitions; + shardresult;sharderror;removerequests;version]) diff --git a/di/dataaccess/test.csv b/di/dataaccess/test.csv new file mode 100644 index 00000000..71a61cad --- /dev/null +++ b/di/dataaccess/test.csv @@ -0,0 +1,139 @@ +action,ms,bytes,lang,code,repeat,minver,comment +comment,,,,,,,setup - load module and accessors +before,0,0,q,da:use`di.dataaccess,1,,load module (pulls in di.asyncdispatch + di.serverselect via use) +before,0,0,q,reqs:{.m.di.0dataaccess.requests},1,,live requests table accessor +before,0,0,q,sr:{.m.di.0dataaccess.shardresults},1,,live shard results dict accessor +comment,,,,,,,setup - override hard deps with mocks so tests are deterministic +before,0,0,q,".m.di.0dataaccess.asyncdispatch:`execquery`execqueryto!({[q;st;jf;pb;t;s]1};{[rt;q;st;jf;pb;t;s]1})",1,,mock di.asyncdispatch (the submitshards stub bypasses it anyway) +before,0,0,q,".m.di.0dataaccess.serverselect:enlist[`getservers]!enlist{[no;lu;req]select servertype from .m.di.0dataaccess.partitions}",1,,mock di.serverselect - all configured partition types are reachable +comment,,,,,,,setup - capturing logger and recording timer (required deps) +before,0,0,q,logged:(),1,,log capture buffer of (level;ctx;msg) triples +before,0,0,q,"mocklog:`info`warn`error!({[c;m]logged,:enlist(`info;c;m)};{[c;m]logged,:enlist(`warn;c;m)};{[c;m]logged,:enlist(`error;c;m)})",1,,capturing binary {[c;m]} logger +before,0,0,q,scheduledjobs:(),1,,timer addjob capture buffer of (id;period;mode) +before,0,0,q,"mocktimer:enlist[`addjob]!enlist{[id;f;p;per;mode;o]scheduledjobs,:enlist(id;per;mode);}",1,,mock di.timer with a recording 6-arg addjob (di.torq's injected timer contract) +before,0,0,q,"(da`init)[`log`timer`partitions!(mocklog;mocktimer;([]servertype:enlist`hdb;coverfrom:enlist -0Wp;coverto:enlist 0Wp))]",1,,init with required log+timer and a single hdb partition covering all time +before,0,0,q,".m.di.0dataaccess.submitshards:{[reqid;shards;timeout](da`shardresult)[reqid;first shards`shardquery;2]}",1,,stub submitshards - feed a fixed result back via shardresult per shard + +comment,,,,,,,exports - both entry points plus the shared lifecycle +true,0,0,q,`init`getdata`getdatafull`execquery`setpartitions`shardresult`sharderror`removerequests`version~key da,1,,module exports the merged api +true,0,0,q,0type deps; '"di.dbwrite: deps must be a dict with a `log key"]; diff --git a/di/dbwrite/init.q b/di/dbwrite/init.q index 6bf98f85..a38146d0 100644 --- a/di/dbwrite/init.q +++ b/di/dbwrite/init.q @@ -3,4 +3,9 @@ \l ::dbwrite.q -export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown]) +/ module version, read from the on-disk VERSION file (the module-local `:::` path convention). +/ di.proc.rdb's and di.proc.wdb's deps.toml both declare di.dbwrite, so di.torq.depcheck needs +/ BOTH the file (pre-load manifest walk) and this export (post-load session audit). +version:first read0`:::VERSION + +export:([init;readcsv;setconfig;getconfig;sort;applyattr;savedown;appenddown;version]) diff --git a/di/depcheck/deps.q b/di/depcheck/deps.q deleted file mode 100644 index 66222c30..00000000 --- a/di/depcheck/deps.q +++ /dev/null @@ -1,4 +0,0 @@ -/ hard module dependencies and their minimum versions, validated by di.depcheck -/ di.depcheck has no hard dependencies - its only runtime dependency (log) is injected via init as a dictionary of -/ functions, following the same convention di.depcheck itself checks other modules against -deps:(`$())!(); diff --git a/di/depcheck/init.q b/di/depcheck/init.q deleted file mode 100644 index eaf3970d..00000000 --- a/di/depcheck/init.q +++ /dev/null @@ -1,9 +0,0 @@ -/ di.depcheck - dependency presence/version, core-contract, and .z.ts ownership auditing for kdb-x modules -/ intended to run once, post-load, after a host process (di.torq) has `use`d every module it needs - see depcheck.md - -\l ::depcheck.q - -/ Module version -version:first read0`:::VERSION - -export:([init;version;checkcontract]) diff --git a/di/depcheck/test.csv b/di/depcheck/test.csv deleted file mode 100644 index bb325fc5..00000000 --- a/di/depcheck/test.csv +++ /dev/null @@ -1,183 +0,0 @@ -action,ms,bytes,lang,code,repeat,minver,comment -comment,,,,,,,setup - load module and a capturing logger -before,0,0,q,depcheck:use`di.depcheck,1,,load di.depcheck module -before,0,0,q,.dc.captbl:([]lvl:`symbol$();ctx:`symbol$();msg:()),1,,log capture table for assertions -before,0,0,q,caplog:`info`warn`error!({[c;m] `.dc.captbl insert (`info;c;m)};{[c;m] `.dc.captbl insert (`warn;c;m)};{[c;m] `.dc.captbl insert (`error;c;m)}),1,,capturing binary logger {[c;m]} - -comment,,,,,,,init - dependency validation -fail,0,0,q,depcheck.init[(::)],1,,init rejects a non-dict deps -fail,0,0,q,depcheck.init[()!()],1,,init rejects missing log key -fail,0,0,q,depcheck.init[enlist[`log]!enlist 42],1,,init rejects a non-dict log value -fail,0,0,q,depcheck.init[enlist[`log]!enlist `info`warn!(caplog`info;caplog`warn)],1,,init rejects a log dict missing the error key -run,0,0,q,.dc.errstr:@[{depcheck.init[()!()]};(::);{x}],1,,capture the error string from a bad init -true,0,0,q,.dc.errstr like "di.depcheck:*",1,,init error is prefixed di.depcheck: - -comment,,,,,,,module metadata - exported version -true,0,0,q,10h=type depcheck.version,1,,version is a string -true,0,0,q,0 zzgb (installed on QPATH) -> zzgc (absent). -comment,,,,,,,zzgb also declares zzga (a cycle), which the visited-set guard must terminate. zzgb itself is a direct dep -comment,,,,,,,of the loaded root so it is checkdeps' domain and must NOT be double-reported by checkgraph -run,0,0,q,.m.di.0zzga.marker:1,1,,fabricate a loaded module di.zzga so it becomes a walk root -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzga "",.dc.qr,""/di/zzgb""; (hsym `$.dc.qr,""/di/zzga/init.q"") 0: enlist ""export:([])""; (hsym `$.dc.qr,""/di/zzga/deps.q"") 0: enlist ""deps:enlist[`di.zzgb]!enlist \""1.0.0\""""",1,,install zzga on QPATH declaring zzgb -run,0,0,q,"(hsym `$.dc.qr,""/di/zzgb/init.q"") 0: enlist ""export:([])""; (hsym `$.dc.qr,""/di/zzgb/deps.q"") 0: enlist ""deps:`di.zzgc`di.zzga!(\""1.0.0\"";\""1.0.0\"")""",1,,install zzgb on QPATH declaring zzgc (missing) and zzga (cycle) -true,0,0,q,"any (.m.di.0depcheck.checkgraph[]) like ""di.zzgc is required transitively by di.zzgb*""",1,,checkgraph surfaces a depth>=2 dependency that does not resolve on QPATH -true,0,0,q,"not any (.m.di.0depcheck.checkgraph[]) like ""di.zzgb is required transitively*""",1,,zzgb (a direct dep of the loaded root) is not double-reported - the cycle also terminated without error -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzga "",.dc.qr,""/di/zzgb""",1,,remove the graph-walk on-disk fixtures (the fabricated .m.di.0zzga is harmless with no deps on disk) - -comment,,,,,,,resolvemodule - QPATH presence resolution without loading, distinct from checkonedep's loaded-check -true,0,0,q,not (::)~.m.di.0depcheck.resolvemodule `di.timer,1,,a real installed module resolves on QPATH -true,0,0,q,(::)~.m.di.0depcheck.resolvemodule `di.doesnotexistanywhere,1,,an absent module resolves to (::) - -comment,,,,,,,a deps.toml that exists but declares no [dependencies] section - the else branch of readdepstoml -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zznodeps""; (hsym `$.dc.qr,""/di/zznodeps/deps.toml"") 0: enlist ""name = \""foo\""""",1,,create a deps.toml with a top-level key but no [dependencies] section -true,0,0,q,0=count (.m.di.0depcheck.readdeps `di.zznodeps) 1,1,,a deps.toml with no [dependencies] section yields an empty merged manifest not a crash -true,0,0,q,"$[.dc.havetoml;0=count (.m.di.0depcheck.readdeps `di.zznodeps) 0;1b]",1,,and no read-failures either - a valid file with nothing declared is not an error (needs di.toml to read the file; no-op pass when absent) -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zznodeps""",1,,remove the no-dependencies scratch fixture - -comment,,,,,,,malformed [dependencies] - a deps.toml where `dependencies` is a scalar not a section. must degrade to a -comment,,,,,,,clean failure line with an empty merged dict, NOT throw out of readdeps's merge and abort the whole walk -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzscalar""; (hsym `$.dc.qr,""/di/zzscalar/deps.toml"") 0: enlist ""dependencies = \""oops\""""",1,,create a deps.toml whose dependencies key is a scalar string -true,0,0,q,"$[.dc.havetoml;any ((.m.di.0depcheck.readdeps `di.zzscalar) 0) like ""di.depcheck: deps.toml for di.zzscalar has a malformed*"";1b]",1,,a non-dict [dependencies] is reported as one clear failure line (no-op pass when di.toml is absent) -true,0,0,q,0=count (.m.di.0depcheck.readdeps `di.zzscalar) 1,1,,and the merged manifest is empty so the merge never throws -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzscalar""",1,,remove the malformed-dependencies scratch fixture - -comment,,,,,,,non-string version value - an unquoted deps.toml version parses to a float; a deps.q version may be an int -comment,,,,,,,or symbol. either is an authoring error reported as its own clear line, never a corrupted concatenated -comment,,,,,,,message or a throw out of parsesemver's `vs`. a single-char string version must NOT trip this guard -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzfloatver""; (hsym `$.dc.qr,""/di/zzfloatver/deps.toml"") 0: (""[dependencies]"";""\""di.timer\"" = 1.0"")",1,,deps.toml with an UNQUOTED version - di.toml parses it as a float -true,0,0,q,"$[.dc.havetoml;any (.m.di.0depcheck.checkmoduledeps `0zzfloatver) like ""di.timer has a non-string minimum version*"";1b]",1,,an unquoted (float) deps.toml version is reported as a non-string version, not a garbage line or a crash (needs di.toml to parse the float; no-op pass when absent) -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzfloatver""",1,,remove the float-version fixture -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzintver""; (hsym `$.dc.qr,""/di/zzintver/deps.q"") 0: enlist ""deps:enlist[`di.timer]!enlist 5""",1,,deps.q with an int version value -true,0,0,q,"any (.m.di.0depcheck.checkmoduledeps `0zzintver) like ""di.timer has a non-string minimum version*""",1,,an int deps.q version is reported as a non-string version too -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzintver""",1,,remove the int-version fixture -run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzonechar""; (hsym `$.dc.qr,""/di/zzonechar/deps.q"") 0: enlist ""deps:enlist[`di.timer]!enlist \""1\""""",1,,deps.q with a legitimate single-char string version -true,0,0,q,"not any (.m.di.0depcheck.checkmoduledeps `0zzonechar) like ""di.timer has a non-string minimum*""",1,,a single-char string version is valid and must NOT be flagged as non-string - the guard does not over-trigger -run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzonechar""",1,,remove the single-char-version fixture diff --git a/di/eodtime/VERSION b/di/eodtime/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/eodtime/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/eodtime/eodtime.md b/di/eodtime/eodtime.md index 402c6ea2..ff53355c 100644 --- a/di/eodtime/eodtime.md +++ b/di/eodtime/eodtime.md @@ -114,8 +114,8 @@ eodtime.setd[1+eodtime.getd[]] ## Usage Example ```q -/ log dep must already match the binary {[c;m]} contract - write your own, or use di.log: -/ logging:use`di.log +/ log dep must already match the binary {[c;m]} contract - write your own, or use di.util.log: +/ logging:use`di.util.log / eodtime.init[logging.logdict] logdep:`info`warn`error!({[c;m]};{[c;m]};{[c;m]}) @@ -145,7 +145,7 @@ k4unit:use`di.k4unit k4unit.moduletest`di.eodtime ``` -The test suite injects a no-op mock logger and a capturing logger that records `(level;msg)` pairs for assertion. It covers: dependency validation (non-dict deps throws; missing `log` key throws; non-dict log value throws; missing `info` key throws; `info`-only log dict succeeds); config defaults and overrides; `getroll` with GMT and non-GMT roll timezones including DST transitions (London winter vs summer, and an overnight DST-transition rollover); `getdailyadjustment` with UTC shortcuts and DST-aware timezones; state setters (`setnextroll`, `setdailyadj`, `setd`) and their corresponding getters; and a six-level log dict (matching `di.log`'s `logdict` shape) accepted as-is by `init`. +The test suite injects a no-op mock logger and a capturing logger that records `(level;msg)` pairs for assertion. It covers: dependency validation (non-dict deps throws; missing `log` key throws; non-dict log value throws; missing `info` key throws; `info`-only log dict succeeds); config defaults and overrides; `getroll` with GMT and non-GMT roll timezones including DST transitions (London winter vs summer, and an overnight DST-transition rollover); `getdailyadjustment` with UTC shortcuts and DST-aware timezones; state setters (`setnextroll`, `setdailyadj`, `setd`) and their corresponding getters; and a six-level log dict (matching `di.util.log`'s `logdict` shape) accepted as-is by `init`. --- diff --git a/di/eodtime/init.q b/di/eodtime/init.q index 027c0e12..48152513 100644 --- a/di/eodtime/init.q +++ b/di/eodtime/init.q @@ -4,4 +4,9 @@ tz:use`di.tz \l ::eodtime.q -export:([init;getd;getnextroll;getdailyadj;getroll;getdailyadjustment;setnextroll;setdailyadj;setd]) +/ module version, read from the on-disk VERSION file (the module-local `:::` path convention). +/ di.proc.tickerplant's deps.toml declares di.eodtime, so di.torq.depcheck needs BOTH the file +/ (pre-load manifest walk) and this export (post-load session audit of a loaded, declared peer). +version:first read0`:::VERSION + +export:([init;getd;getnextroll;getdailyadj;getroll;getdailyadjustment;setnextroll;setdailyadj;setd;version]) diff --git a/di/eodtime/test.csv b/di/eodtime/test.csv index 1fdd0e36..2f91097f 100644 --- a/di/eodtime/test.csv +++ b/di/eodtime/test.csv @@ -80,8 +80,8 @@ run,0,0,q,eodtime.init[enlist[`log]!enlist `info`warn!(logdep`info;logdep`warn)] run,0,0,q,.test.err:@[{eodtime.init[()!()]};(::);{x}],1,1,capture error string from init with missing log dep true,0,0,q,.test.err like "di.eodtime:*",1,1,error is prefixed di.eodtime: -comment,,,,,,,init - accepts any dict already shaped to the binary {[c;m]} contract (e.g. di.log's logdict) -run,0,0,q,sixlvllog:`trace`debug`info`warn`error`fatal!({[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]}),1,1,hand-built six-level dict matching di.log's logdict shape +comment,,,,,,,init - accepts any dict already shaped to the binary {[c;m]} contract (e.g. di.util.log's logdict) +run,0,0,q,sixlvllog:`trace`debug`info`warn`error`fatal!({[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]};{[c;m]}),1,1,hand-built six-level dict matching di.util.log's logdict shape run,0,0,q,eodtime.init[`log`rolltimezone!(sixlvllog;`$"GMT")],1,1,superset log dict accepted as-is - only info/warn/error are used comment,,,,,,,log call verification - capturing logger sees init message with binary {[c;m]} args diff --git a/di/handlers/init.q b/di/handlers/init.q deleted file mode 100644 index 925fb717..00000000 --- a/di/handlers/init.q +++ /dev/null @@ -1,5 +0,0 @@ -/ di.handlers - central registry for KDB-X .z.* connection-lifecycle callbacks - -\l ::handlers.q - -export:([init;register;remove;list;version]) diff --git a/di/log/init.q b/di/log/init.q deleted file mode 100644 index cd68a4e4..00000000 --- a/di/log/init.q +++ /dev/null @@ -1,4 +0,0 @@ -// structured logger - default log dependency for di.* modules -\l ::log.q - -export:([createlog;logdict;trace;debug;info;warn;error;fatal]) diff --git a/di/pqx/pqx.md b/di/pqx/pqx.md index d213d956..e69c7940 100644 --- a/di/pqx/pqx.md +++ b/di/pqx/pqx.md @@ -48,11 +48,11 @@ alongside it. The `log` dependency must be passed to `init` inside a dict keyed on `` `log ``. `init` throws immediately if `log` is absent, is not a dict, or is missing any of `info`/`warn`/`error`. The value must already conform to the binary `{[c;m]}` contract — `init` performs no adaptation, so a raw -monadic `kx.log` instance must be wrapped by the caller first. Build the dict from `di.log`, or +monadic `kx.log` instance must be wrapped by the caller first. Build the dict from `di.util.log`, or hand-roll one. ```q -logger:use`di.log +logger:use`di.util.log logdep:`info`warn`error!(logger.info;logger.warn;logger.error) pqx:use`di.pqx pqx.init[enlist[`log]!enlist logdep] @@ -253,7 +253,7 @@ pqx.init[enlist[`log]!enlist logdep] | `getmanifest[]` | Return the manifest accumulated so far across all `extract` calls. | | `readfile[path;readopt]` | Read a single file back, reattaching its `virtualcols`/`date` values reconstructed from its path (see Options). | | `buildvirtualtable[hdbdir;tname;levels]` | Compose every file under `hdbdir/tname/` into one queryable virtual table, with each hive-style path segment in `levels` reconstructed and typed per its declared type char (see Virtual Tables). | -| `version` | The module version string, read from the `VERSION` file at load time. Consumed by `di.depcheck`. | +| `version` | The module version string, read from the `VERSION` file at load time. Consumed by `di.torq.depcheck`. | The remaining exports — `checkandconvertcols`, `estimate`, `plan`, `writefile`, `tryfn`, `checkvirtuallevels`, `checkvirtualtypes` — are internal pipeline steps of @@ -272,7 +272,7 @@ required key. ### `version` The module version string, read from the `VERSION` file at load time (fails loudly if that file -is missing, unreadable, or empty). Consumed by `di.depcheck`. +is missing, unreadable, or empty). Consumed by `di.torq.depcheck`. ```q pqx.version / "0.1.0" ``` @@ -326,7 +326,7 @@ Only useful for a file written with `virtualcols` set, or to recover the `date` pqx:use`di.pqx // Wire the log dependency (once per process) -logger:use`di.log +logger:use`di.util.log pqx.init[logger.logdict] // Write `trade` for 2025.07.15, overriding the target file size and codec diff --git a/di/pqx/pqx.q b/di/pqx/pqx.q index 83c872d8..98a99208 100644 --- a/di/pqx/pqx.q +++ b/di/pqx/pqx.q @@ -448,7 +448,7 @@ getdefault:{[] init:{[deps] / wire the injected logger (required, no fallback). deps: a `log - / key holding a binary `info`warn`error dict of {[c;m]} loggers (di.log or hand-rolled; a monadic + / key holding a binary `info`warn`error dict of {[c;m]} loggers (di.util.log or hand-rolled; a monadic / kx.log instance must be wrapped first). e.g. di.pqx.init[enlist[`log]!enlist logdep] if[99h<>type deps; '"di.pqx: deps must be a dict with a `log key"]; diff --git a/di/proc/gateway/VERSION b/di/proc/gateway/VERSION new file mode 100644 index 00000000..0ea3a944 --- /dev/null +++ b/di/proc/gateway/VERSION @@ -0,0 +1 @@ +0.2.0 diff --git a/di/proc/gateway/deps.toml b/di/proc/gateway/deps.toml new file mode 100644 index 00000000..6c64fb2b --- /dev/null +++ b/di/proc/gateway/deps.toml @@ -0,0 +1,9 @@ +# Peer modules di.gateway `use`s, with the minimum version each must be at. Ships WITH the +# module (versioned lockstep) and is validated transitively at startup by di.torq.depcheck's +# manifest walk (di.torq.init) - see di/depcheck/depcheck.md. Not the app's install manifest; +# that is TORQXAPPHOME/deps.toml. +[dependencies] +"di.torq.servers" = "0.3.0" # requires the INJECTED-servers contract (deps`servers) +"di.serverselect" = "0.1.0" +"di.asyncdispatch" = "0.1.0" +"di.dataaccess" = "0.2.0" diff --git a/di/proc/gateway/gateway.md b/di/proc/gateway/gateway.md new file mode 100644 index 00000000..fa0b739a --- /dev/null +++ b/di/proc/gateway/gateway.md @@ -0,0 +1,90 @@ +# di.proc.gateway + +A query gateway: the single point a client queries, which routes the query across backend +processes (rdb, hdb, …), joins the per-backend results, and replies. Thin **orchestration glue** +over three modules: + +| Module | Role | Origin | +|---|---|---| +| `di.torq.servers` | discover + connect to the backend processes | TorqX | +| `di.serverselect` | registry of backends + servertype/attribute routing | vendored (kdbx-modules) | +| `di.asyncdispatch` | async scatter-gather: queue → dispatch → collect → join → reply | vendored (kdbx-modules) | + +Ported from the `.gw` orchestration in `TorQ/code/processes/gateway.q`; the engine and routing +are the two vendored modules, so di.proc.gateway itself is small. + +## Dependencies + +- **Injected** (from di.torq): `log`, `timer`, `handlers`. +- **Hard** (`use`-imported): `di.torq.servers`, `di.serverselect`, `di.asyncdispatch`. + +Both vendored modules take the **binary `{[c;m]}`** log dep — the same contract di.torq injects — +so di.proc.gateway passes the injected `log` straight through (no adapter, unlike di.dbwrite). + +## Config + +```toml +backendtypes = "rdb hdb" # proctype(s) to connect to and route queries across (default `rdb`hdb) +synccallsallowed = false # allow deferred-sync execquery (passed to di.asyncdispatch) +errorprefix = "error: " # prefix on error strings returned to clients +``` + +## Client API (published at root `.gw.*`) + +- `.gw.asyncexec[query;servertypes]` — run `query` on one backend of each servertype, `raze` the + results, reply to the client. Deferred-sync: the client does + `neg[h](`.gw.asyncexec;query;`rdb`hdb); h[]`. +- `.gw.asyncexecjpt[query;servertypes;join;postback;timeout]` — full control: custom join function, + postback wrapper (`()` for none), and per-query timeout. + +`servertypes` is a **symbol list** (e.g. `` `rdb`hdb ``) or an **attribute dict** (routed via +di.serverselect — see the scope note). `query` is any value passed to `value` on the backend +(a q string, or a `(func;args…)` parse tree). + +## EOD reload gate (published at root `.gw.reload`) + +The wdb calls `(`.gw.reload;`reloadstart)` before moving its partition into the hdb and +`(`.gw.reload;`reloadend)` after the hdb/rdb have reloaded (di.proc.wdb's `informgateway` already sends +these — building this module makes that loop live). While gated, new queries are rejected with a +retry message so none straddle the rdb-drop / hdb-reload window; `reloadend` clears the gate and +refreshes the backend registry. + +## How it wires together (init) + +1. init di.serverselect + di.asyncdispatch with the injected `log`. +2. point asyncdispatch's **server source** at serverselect (`setavailableservers`), so serverselect + is the single registry and asyncdispatch dispatches against it. +3. publish asyncdispatch's result/error callbacks at `.gw.addserverresult`/`.gw.addservererror` and + `setcallbacks` to them (the vendored asyncdispatch bakes these into the shipped executor, so + backends need no cooperating code — see the patch note in di.asyncdispatch). +4. connect to `backendtypes` via di.torq.servers and register them into serverselect. +5. register `.z.po`/`.z.pc` callbacks via the handlers dep (client tracking; backend/client + disconnect cleanup + serverselect deactivate). `.z.ps` `exec` defaults to `value`, so client + async calls and backend async replies dispatch without extra wiring. +6. publish `.gw.*` entry points; schedule asyncdispatch housekeeping (`checktimeout`, + `removequeries`, `removeinactive`, `removeclients`) on the injected timer. + +## Not included (v1) / notes + +- **Attribute routing needs backend attribute reporting.** di.serverselect can route by an attribute + dict (e.g. which servers hold a date range), but backends must report those attributes and + di.torq.servers/di.proc.rdb/di.proc.hdb don't yet — so v1 registers backends with **empty attributes** and + attribute-dict queries degrade/err until that plumbing lands. Servertype-list routing is the v1 + happy path. +- **No per-backend query serialisation.** With the server source pointed at di.serverselect (which + has no `inuse` state), asyncdispatch doesn't hold one-query-per-backend. Fine for POC volumes; + backends serialise internally. +- **Deferred:** di.dataaccess (typed `getdata` + map-reduce date-splitting), pure-synchronous + `syncexec`, permissions, kxdash. **Removed:** finspace. + +## Testing + +`test.csv` (k4unit) covers the dependency contract (init errors without log/timer/handlers) and the +export surface. The full client → gateway → scatter-gather → rdb+hdb → join → reply flow (and the +EOD reload gate with the wdb) is proven in the **TorqX-POC end-to-end** +(`torqx.sh start tickerplant1 hdb feed1 rdb1 wdb1 gateway1`). + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.proc.gateway +``` diff --git a/di/proc/gateway/gateway.q b/di/proc/gateway/gateway.q new file mode 100644 index 00000000..af2b884c --- /dev/null +++ b/di/proc/gateway/gateway.q @@ -0,0 +1,141 @@ +/ di.proc.gateway - query gateway. Orchestration glue wiring three pieces into a queryable front end: +/ di.torq.servers - discover + connect to backend processes (rdb/hdb) +/ di.serverselect - registry of backends + servertype/attribute routing (VENDORED) +/ di.asyncdispatch - async scatter-gather: queue -> dispatch -> collect -> join -> reply (VENDORED) +/ Publishes .gw.* entry points; a client sends a query + a list of servertypes, the gateway routes it +/ to one backend of each type, joins the per-server results, and replies (deferred-sync/async). +/ Ported from the .gw orchestration in TorQ/code/processes/gateway.q; the engine + routing are the +/ two vendored modules, so di.proc.gateway is thin glue. +/ --- +/ Scope (v1): async / deferred-sync only. Routing by servertype list (the happy path) and by +/ attribute dict (via di.serverselect) - but attribute routing needs backends to REPORT attributes +/ (tables/date-ranges), which di.torq.servers/di.proc.rdb/di.proc.hdb don't do yet, so v1 registers backends with +/ EMPTY attributes and attribute-dict queries degrade/err until that plumbing lands. Deferred: +/ di.dataaccess (typed getdata + map-reduce), pure-sync syncexec, permissions, kxdash. Removed: +/ finspace. Known v1 limitation: with the server source pointed at di.serverselect (which has no +/ inuse state), there is no per-backend one-query-at-a-time serialisation - fine for POC volumes. +/ --- +/ Module-namespace note: the .gw.* functions and the asyncdispatch callbacks are published at REAL +/ root names (set[`.gw...;...]) - use mangles module code into a private namespace, so a remote +/ client call or a backend's async result reply must resolve at root. Same pattern as .hdb.reload. + +assym:{[x] $[11h=abs type x;x;`$x]} +aslist:{[x] $[0>type x;enlist x;x]} +/ a token-list config (e.g. backendtypes/reloadorder): space-separated string, single symbol, +/ symbol list, or list of strings -> always a symbol list +astoklist:{[x] $[10h=type x;`$" " vs x;-11h=type x;enlist x;11h=type x;x;`$x]} + +/ di.dataaccess routing coverage from the current date: rdb holds today (>= midnight), hdb holds +/ history (< midnight). Built at init and re-evaluated at EOD reloadend (after the wdb moves today's +/ partition into the hdb, ".z.d" has advanced so "today" now correctly falls to the hdb). +buildpartitions:{[] mid:`timestamp$.z.d; ([]servertype:`rdb`hdb;coverfrom:(mid;-0Wp);coverto:(0Wp;mid-1))} + +/ resolve a client's servertype argument to a plain servertype symbol list. +/ symbol / symbol list -> itself. attribute dict (99h) -> the distinct servertypes of the servers +/ di.serverselect matches (asyncdispatch dispatches by servertype, one handle per type). +resolvetypes:{[st] + $[99h=type st; + distinct exec servertype from (.z.m.srvsel`getserverstable)[] where serverid in raze (.z.m.srvsel`getserverids)[st]; + aslist assym st] + } + +/ (re)register the connected backends from di.torq.servers into di.serverselect (idempotent - it skips +/ already-active handles). v1 registers with empty attributes (no backend attribute reporting yet). +registerbackends:{[] + ct:raze {[t] select w,proctype,procname,hpup from (.z.m.svc`getservers)[t] where not null w} each .z.m.backendtypes; + if[count ct; + ct:update attributes:count[ct]#enlist()!() from ct; + (.z.m.srvsel`addserversfromtable)[.z.m.backendtypes;ct]; + .z.m.log[`info][`gateway;"registered ",(string count ct)," backend server(s): ",", " sv string exec distinct proctype from ct]]; + } + +/ client entry point (published at root as .gw.asyncexecjpt): full control over join/postback/timeout. +/ protected so a routing/dispatch error becomes a formatted reply to the client rather than an +/ uncaught error on the async handler. +asyncexecjpt:{[query;servertype;join;postback;timeout] + if[.z.m.eod;@[neg .z.w;.z.m.errorprefix,"gateway in eod reload - retry shortly";()];:()]; + .[{[q;s;j;p;t] (.z.m.ad`execquery)[q;resolvetypes s;j;p;t;0b]}; + (query;servertype;join;postback;timeout); + {[e] @[neg .z.w;.z.m.errorprefix,e;()]}]; + } + +/ client entry point (published at root as .gw.asyncexec): raze results, no postback, no timeout. +asyncexec:{[query;servertype] asyncexecjpt[query;servertype;raze;();0Wn]} + +/ EOD reload gate (published at root as .gw.reload) - the wdb calls (`.gw.reload;`reloadstart) before +/ moving its partition into the hdb and (`.gw.reload;`reloadend) after the hdb/rdb have reloaded. +/ While gated, new queries are rejected (client retries) so none straddle the rdb-drop/hdb-reload +/ window. v1 rejects rather than queues-and-resumes; on reloadend it refreshes the backend registry. +reload:{[msg] + $[msg~`reloadstart; + [.z.m.eod:1b; .z.m.log[`info][`gateway;"eod reload start - holding new queries"]]; + msg~`reloadend; + [.z.m.eod:0b; registerbackends[]; (.z.m.da`setpartitions)[buildpartitions[]]; .z.m.log[`info][`gateway;"eod reload end - resuming queries"]]; + .z.m.log[`warn][`gateway;"unknown .gw.reload message: ",string msg]]; + } + +init:{[config;deps] + if[not all `log`timer`handlers`servers in key deps;'"di.proc.gateway: log, timer, handlers and servers dependencies are required (servers is injected by di.torq)"]; + .z.m.log:deps`log; + .z.m.timer:deps`timer; + .z.m.backendtypes:$[`backendtypes in key config;astoklist config`backendtypes;`rdb`hdb]; + .z.m.errorprefix:$[`errorprefix in key config;config`errorprefix;"error: "]; + .z.m.eod:0b; + + / di.serverselect - registry + routing. log dep is binary {[c;m]}, matching di.torq's inject. + .z.m.srvsel:use`di.serverselect; + (.z.m.srvsel`init)[enlist[`log]!enlist deps`log]; + + / di.asyncdispatch - scatter-gather engine. Point its server SOURCE at di.serverselect (no inuse + / column there, so excludeinuse is ignored - see the scope note). Publish its result/error + / callbacks at root .gw.* and tell it to reply to those names (baked into the shipped executor by + / the vendor patch, so backends need no cooperating code). + .z.m.ad:use`di.asyncdispatch; + adcfg:enlist[`log]!enlist deps`log; + if[`synccallsallowed in key config;adcfg[`synccallsallowed]:`boolean$config`synccallsallowed]; + (.z.m.ad`init)[adcfg]; + / NB: param is `sel`, NOT `ss` - `ss` is the built-in string-search function and q would + / resolve ss[...] to the builtin instead of the projected serverselect dict (throws 'match). + (.z.m.ad`setavailableservers)[{[sel;excludeinuse] select handle,servertype from sel[`getserverstable][] where active}[.z.m.srvsel]]; + set[`.gw.addserverresult;.z.m.ad`addserverresult]; + set[`.gw.addservererror;.z.m.ad`addservererror]; + (.z.m.ad`setcallbacks)[`.gw.addserverresult;`.gw.addservererror]; + + / di.torq.servers - connect out to the backend process types, then register them into serverselect. + / Uses the INJECTED di.torq.servers (di.torq already ran init); we call only startup with our own + / backend connection list, and getservers off the same injected instance (registerbackends). + .z.m.svc:deps`servers; + sconfig:config,(enlist`connections)!enlist .z.m.backendtypes; + (.z.m.svc`startup)[sconfig]; + registerbackends[]; + + / di.dataaccess - the getdata query-normalisation layer, on top of the SAME asyncdispatch + / instance (idempotent use) so it dispatches via the callbacks/registry set up above. Partition + / coverage for routing is built from .z.d (buildpartitions) and refreshed at EOD reloadend via + / (.z.m.da`setpartitions), so post-roll queries for the just-saved day route to the hdb not the rdb. + .z.m.da:use`di.dataaccess; + (.z.m.da`init)[`log`timer`partitions!(deps`log;deps`timer;buildpartitions[])]; + + / handler callbacks via the injected handlers dep (di.torq.handlers): track client connect, and on any + / handle close clean up whichever role it was - backend (asyncdispatch in-flight cleanup + + / serverselect deactivate) or client (asyncdispatch orphan-query cleanup). Each is a no-op for + / the other role, so calling all three on every close is safe. + hl:deps`handlers; + (hl`register)[`.z.po;`;`gateway;10;{[wh] (.z.m.ad`addclientdetails)[wh]}]; + (hl`register)[`.z.pc;`;`gateway;10;{[wh] (.z.m.ad`removeserverhandle)[wh]; (.z.m.ad`removeclienthandle)[wh]; (.z.m.srvsel`setserveractive)[wh;0b]}]; + + / publish the client entry points + the eod reload gate at root. .gw.getdata is the + / normalised query layer (di.dataaccess); the raw asyncexec/asyncexecjpt route query strings. + set[`.gw.asyncexec;asyncexec]; + set[`.gw.asyncexecjpt;asyncexecjpt]; + set[`.gw.getdata;.z.m.da`getdata]; + set[`.gw.reload;reload]; + + / housekeeping timers (asyncdispatch leaves scheduling to the caller). mode 1h period = seconds. + (.z.m.timer`addjob)[`gwtimeout;{(.z.m.ad`checktimeout)[]};();5;1h;()!()]; + (.z.m.timer`addjob)[`gwrmqueries;{(.z.m.ad`removequeries)[0D00:30]};();60;1h;()!()]; + (.z.m.timer`addjob)[`gwrminactive;{(.z.m.ad`removeinactive)[0D01:00]};();300;1h;()!()]; + (.z.m.timer`addjob)[`gwrmclients;{(.z.m.ad`removeclients)[0D01:00]};();300;1h;()!()]; + + .z.m.log[`info][`gateway;"initialised, backendtypes=",(", " sv string .z.m.backendtypes)]; + } diff --git a/di/proc/gateway/init.q b/di/proc/gateway/init.q new file mode 100644 index 00000000..ff6741d7 --- /dev/null +++ b/di/proc/gateway/init.q @@ -0,0 +1,5 @@ +\l ::gateway.q + +version:first read0`:::VERSION + +export:([init;asyncexec;asyncexecjpt;reload;version]) diff --git a/di/proc/gateway/test.csv b/di/proc/gateway/test.csv new file mode 100644 index 00000000..21380f84 --- /dev/null +++ b/di/proc/gateway/test.csv @@ -0,0 +1,9 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,gw:use`di.proc.gateway,1,,load module +before,0,0,q,mlog:`info`warn`error!(3#enlist {[c;m]}),1,,a minimal (binary) log dep dict + +fail,0,0,q,gw.init[()!();()!()],1,,init without any deps must error +fail,0,0,q,gw.init[()!();(enlist`log)!enlist mlog],1,,init with log but no timer/handlers deps must error + +true,0,0,q,`init`asyncexec`asyncexecjpt`reload`version~key gw,1,,module exports init/asyncexec/asyncexecjpt/reload/version +true,0,0,q,0 all tables, all syms +# ignorelist omitted -> `heartbeat`logmsg (not saved at EOD) +# sortcsv (optional) -> di.dbwrite sort/attribute config; else dbwrite's default (time asc) +``` + +Set `reloadenabled = true` **only** when a wdb is present in the stack — otherwise the EOD +writedown is deferred to a wdb that never calls back, and the data is never persisted. + +The **schema comes from the tickerplant** (via `subdetails`), not a local `database.q` — +di.subscriptions defines the tables at root from what the TP returns. + +## Behaviour + +- **Startup**: `di.torq.servers` connects to the TP + HDB(s); block until a TP is up + (`waitfortype`); `di.subscriptions.subscribe` registers for live data and replays the + day's log up to the pre-subscription count. +- **Accumulate** (`upd`, published at root): a **root-namespace-safe** append — upserts a + table payload (live) or a list-of-columns payload (replay) into the root table via + `@[`.;t;…]`. Set at root **before** subscribing so replay drives it too. +- **End of day** (`endofday[date]`, published at root, also `.u.end`): the tickerplant + broadcasts `(`endofday;date)` at roll (see below). Behaviour depends on `reloadenabled`: + - **standalone** (`0b`, default): saves every non-ignored root table to `hdbdir` for `date` + (`di.dbwrite.savedown` — enumerate, splay, sort, attr, gc), clears each (`@[`.;t;0#]`), + then tells every connected HDB to `.hdb.reload[]`. + - **wdb-fronted** (`1b`): a wdb owns the writedown, so di.proc.rdb only **snapshots** the + per-table row counts (`.z.m.eodtabcount`) and escapes — the data stays live and + queryable. No save, no clear, no HDB notify. It waits for the wdb's `reload[date]`. +- **Reload** (`reload[date]`, published at root): the IPC entry point the **wdb** calls once + it has persisted the prior day. Drops exactly the snapshotted row count from each table + (`n _`, keeping the new day's ticks that arrived since EOD), reapplies attributes (the drop + loses `` `g# `` etc.), garbage-collects, and clears the snapshot. Harmless if never called + (standalone rdbs simply never receive it). + +## RDB / WDB interaction (why `reload` exists) + +When both an rdb and a wdb subscribe to the same tickerplant, the wdb owns the on-disk +writedown and the rdb keeps the prior day **in memory, queryable**, until the wdb confirms +the data is safely on disk. The handshake at roll: + +1. the tp broadcasts `(`endofday;date)` to both. The rdb (`reloadenabled=1b`) snapshots its + row counts and returns — nothing saved, nothing cleared. New-day ticks keep landing. +2. the wdb flushes its buffer to disk, sorts, moves the partition into the hdb, then calls + `(`reload;date)` on each rdb (and `.hdb.reload` on each hdb). +3. the rdb's `reload` drops the first `eodtabcount[t]` rows of each table — exactly the prior + day the wdb just persisted — leaving the new day intact. + +This mirrors `TorQ/code/processes/rdb.q`'s `reloadenabled`/`dropfirstnrows`. Responsibility +for the writedown is **explicit config** (`reloadenabled`), not auto-detection: the rdb never +probes for a wdb's existence (fail-fast / explicit-config, per the TorQ conventions). + +## The EOD trigger (TP-driven, dated) + +The RDB's writedown is triggered **by the tickerplant**, not a local timer — so it saves +exactly the day's data, only after the TP has sent its last message for the day. This +required a fix to di.pubsub (vendored into TorqX): `callendofday` now broadcasts +`(`endofday;date)` instead of a bare `` `endofday`` symbol. A bare async symbol is **not** +applied by a default `.z.ps` (it returns the function, doesn't call it) and carries no +partition date; the 2-list form is applied as `endofday[date]` (classic `.u.end` style). +Feed this fix upstream when di.pubsub is next touched. + +## Not included (future / other-process / deprecated) + +- **Gateway** attribute push + query-partition tracking (`rdbpartition`/`parvaluesrc` — + that machinery exists *only* so a gateway knows which dates the RDB holds; a standalone + RDB doesn't need it). Note TorQ's `reloadenabled` EOD branch *also* pushes EOD attributes + to the gateway; that half is deferred here with the rest of the gateway support. +- **Subscription filters** (`subfiltered`) — experimental/incomplete upstream. +- **FinSpace/AWS** — stripped entirely. + +## Module-namespace notes + +A `use`-loaded module can't create/populate root tables via bare symbols (they land in the +module's private namespace; a bare `insert` under `-11!` replay does too). di.proc.rdb therefore +reads root tables with bare `value t` (bare **reads** fall through to root), but **writes** +and **clears** target root explicitly via `@[`.;…]`, and its `upd` is root-safe. + +## Testing + +`test.csv` (k4unit) covers the dependency contract (init errors without `log`/`timer`) and +the export surface. The full subscribe → replay → live-capture → EOD-save → HDB-reload +flow is proven in the **TorqX-POC end-to-end** (`torqx.sh start tickerplant1 hdb feed1 +rdb1`): the RDB replays the tp log on startup, accumulates live trade/quote, and on a +forced tickerplant `endofday` writes the partition to the HDB (verified on disk), clears, +and the HDB reloads to see it. + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.proc.rdb +``` diff --git a/di/proc/rdb/rdb.q b/di/proc/rdb/rdb.q new file mode 100644 index 00000000..9f27afd9 --- /dev/null +++ b/di/proc/rdb/rdb.q @@ -0,0 +1,152 @@ +/ di.proc.rdb - real-time database. Subscribes to a tickerplant (via di.subscriptions), +/ replays the day's tp log to recover intraday state, accumulates live updates in memory, +/ and at end of day writes each table down to the HDB (via di.dbwrite), clears it, and +/ tells the HDB(s) to reload. Ported from the CRITICAL path of TorQ/code/processes/rdb.q. +/ --- +/ Scope (v1, critical only - see the rdb.q Chesterton's-Fence audit): subscribe -> replay +/ -> accumulate -> savedown -> hdb reload. Two EOD modes, selected by config reloadenabled: +/ - standalone (0b, default): save every table to the hdb, clear it, reload the hdb(s). +/ - wdb-fronted (1b): a wdb owns the writedown; at EOD we only SNAPSHOT the per-table row +/ counts and escape (data stays live+queryable), then the wdb calls reload[date] over +/ IPC and we drop exactly the prior day, keeping the new day's ticks (dropfirstnrows). +/ NOT included (future/other-process): gateway attribute push, query-partition tracking +/ (rdbpartition/parvaluesrc - that exists only for a gateway), subscription filters, and +/ (deprecated) all finspace/aws paths. +/ --- +/ Module-namespace notes (see di.subscriptions for the full story): reads of root tables +/ use bare `value t` (bare reads fall through to root); writes/clears target root +/ explicitly via @[`.;..] because a bare write from a use-loaded module (or under -11!) +/ lands in the module's private namespace. + +/ config coercion (values are symbols from .q settings or strings from .toml) +assym:{[x] $[11h=abs type x;x;`$x]} +aslist:{[x] $[0>type x;enlist 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). +apphome:{getenv[`TORQXAPPHOME]} +datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]} + +/ resolve 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 drop nothing + reapplyattrs'[st;attrs st]; + .z.m.eodtabcount:()!(); / so a repeat reload is a no-op + .Q.gc[]; + .z.m.log[`info][`rdb;"reload complete, dropped prior-day rows for: ",(", " sv string st)]; + } + +init:{[config;deps] + if[not `log in key deps;'"di.proc.rdb: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.proc.rdb: timer dependency is required - see di.timer"]; + if[not `servers in key deps;'"di.proc.rdb: servers dependency is required - injected by di.torq, see di.torq.servers"]; + .z.m.log:deps`log; + .z.m.timer:deps`timer; + .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.ignorelist:$[`ignorelist in key config;aslist assym config`ignorelist;`heartbeat`logmsg]; + .z.m.hdbdir:$[`hdbdir in key config;resolvedir[datahome[];config`hdbdir];datahome[],"/hdb"]; + .z.m.reloadenabled:$[`reloadenabled in key config;`boolean$config`reloadenabled;0b]; + .z.m.eodtabcount:()!(); / prior-day snapshot, populated at EOD when reloadenabled + 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]; + + / publish the root-safe upd BEFORE subscribing (replay drives it too) + @[`.;`upd;:;updfn]; + + / connect to the tickerplant + hdb(s) via the INJECTED di.torq.servers (di.torq already ran its + / init - a shared, once-init'd connection registry). We only call startup, handing it our + / own connection list; the lookup fns (waitfortype/gethandlebytype/getservers) come off the + / same injected instance. + .z.m.svc:deps`servers; + sconfig:config,(enlist`connections)!enlist distinct .z.m.tptypes,.z.m.hdbtypes; + (.z.m.svc`startup)[sconfig]; + + / block until a tickerplant is up, then subscribe (subdetails + replay) + tpt:first .z.m.tptypes; + if[not (.z.m.svc`waitfortype)[tpt;timeout;500]; + '"di.proc.rdb: no ",(string tpt)," connection within ",(string timeout),"ms - cannot start rdb"]; + tph:(.z.m.svc`gethandlebytype)[tpt;`any]; + .z.m.subs:use`di.subscriptions; + (.z.m.subs`init)[config;deps]; + sd:(.z.m.subs`subscribe)[tph;subscribeto;subscribesyms;replaylog]; + .z.m.log[`info][`rdb;"subscribed; replayed ",(string sd`rowcount)," message(s), partition date ",string sd`date]; + + / di.dbwrite for savedown (optional sort.csv sort/attr config). Takes the injected binary + / (ctx;msg) log dep directly - no adapter, since di.dbwrite now uses the same contract. + .z.m.dbw:use`di.dbwrite; + (.z.m.dbw`init)[enlist[`log]!enlist deps`log]; + if[`sortcsv in key config;(.z.m.dbw`readcsv)[resolvedir[apphome[];config`sortcsv]]]; + + / publish the EOD entry points at root (the TP calls endofday[date]; .u.end is the alias). + / reload[date] is the wdb's IPC entry point when reloadenabled (harmless if never called). + @[`.;`endofday;:;endofday]; + @[`.;`.u.end;:;endofday]; + @[`.;`reload;:;reload]; + .z.m.log[`info][`rdb;"initialised, hdbdir=",.z.m.hdbdir,", reloadenabled=",string .z.m.reloadenabled]; + } diff --git a/di/proc/rdb/test.csv b/di/proc/rdb/test.csv new file mode 100644 index 00000000..5c8ffb4c --- /dev/null +++ b/di/proc/rdb/test.csv @@ -0,0 +1,9 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,rdb:use`di.proc.rdb,1,,load module +before,0,0,q,mlog:`info`warn`error!(3#enlist {[c;m]}),1,,a minimal (dyadic) log dep dict + +fail,0,0,q,rdb.init[()!();()!()],1,,init without the log dependency must error +fail,0,0,q,rdb.init[()!();(enlist`log)!enlist mlog],1,,init with log but no timer dependency must error + +true,0,0,q,`init`endofday`reload`version~key rdb,1,,module exports init/endofday/reload/version +true,0,0,q,0TP->subscriber delivery is covered by the torqx.sh end-to-end, not here: +/ pubsub publishes via async -25!, which does not flush inside a synchronous test. + +BASE:"/tmp/di_tickerplant_k4unit" + +/ mock log +calls:([]lvl:`symbol$();ctx:`symbol$();msg:()) +resetcalls:{[] `calls set ([]lvl:`symbol$();ctx:`symbol$();msg:()); } +mocklogfn:{[lvl;ctx;msg] `calls insert (lvl;ctx;msg); } +mocklog:{[] `info`warn`error!(mocklogfn[`info;;];mocklogfn[`warn;;];mocklogfn[`error;;])} + +/ mock timer - records scheduled jobs +timercalls:([]id:`symbol$();period:`int$();mode:`short$()) +resettimer:{[] `timercalls set ([]id:`symbol$();period:`int$();mode:`short$()); } +mockaddjob:{[id;func;params;period;mode;opts] `timercalls insert (id;`int$period;mode); } +mocktimer:{[] enlist[`addjob]!enlist mockaddjob} + +deps:{[] `log`timer!(mocklog[];mocktimer[])} + +setupfixture:{[] + system "rm -rf ",BASE; + {system "mkdir -p ",BASE,"/",x} each ("log";"batchlog";"eodlog";"replog";"subdlog"); + setenv[`TORQXAPPHOME;BASE]; + / good schema: trade + quote, both time,sym first + (hsym`$BASE,"/database.q") 0: ( + "trade:([]time:`timestamp$();sym:`symbol$();price:`float$();size:`int$())"; + "quote:([]time:`timestamp$();sym:`symbol$();bid:`float$();ask:`float$())"); + / bad schema: a table with neither time nor sym first + (hsym`$BASE,"/badschema.q") 0: enlist "widgets:([]id:`int$();name:`symbol$())"; + } +teardownfixture:{[] system "rm -rf ",BASE; } + +/ config builders (kept out of test.csv: they contain commas/backticks) +immcfg:{[] `publishmode`tplogdir`schemafile!(`immediate;BASE,"/log";BASE,"/database.q")} +batchcfg:{[] `publishmode`pubperiod`tplogdir`schemafile!(`batched;2;BASE,"/batchlog";BASE,"/database.q")} +nologcfg:{[] `publishmode`schemafile!(`immediate;BASE,"/database.q")} +badcfg:{[] `publishmode`schemafile!(`immediate;BASE,"/badschema.q")} +replaycfg:{[] `publishmode`tplogdir`schemafile!(`batched;BASE,"/replog";BASE,"/database.q")} +subdcfg:{[] `publishmode`tplogdir`schemafile!(`immediate;BASE,"/subdlog";BASE,"/database.q")} + +/ feed n trade rows through the published root upd (columns form, single record each) +feedtrades:{[n] {upd[`trade;(.z.p;`$"S",string x;1.0*x;`int$x)]} each til n; } + +/ message count in a log dir's current-day log (GMT date, matching eodtime GMT config) +logcount:{[dir] c:-11!(-2;hsym`$dir,"/tp",string "d"$.z.p); $[0>type c;c;first c]} + +/ assertion helpers factored here because they contain raw commas (which split CSV fields) +loghas:{[sub;n] n=logcount[BASE,"/",sub]} +flushperiodok:{[] 2=first exec period from timercalls where id=`tpflush} +rolledfile:{[sub;date] not ()~key hsym`$BASE,"/",sub,"/tp",string date} + +/ init helpers that store handles / state for assertions +doinit:{[cfg] resetcalls[]; resettimer[]; (tk`init)[cfg;deps[]]; } +initbad:{[] (tk`init)[badcfg[];deps[]]; } / expected to throw (used by a fail row) + +scheduled:{[id] id in exec id from timercalls} + +/ subdetails: after feeding 5 trades, the subscription-details call reports rowcount=5, +/ the publishable tables + their schemas, and the correct log file / date. (Registration +/ targets .z.w=0 in-process; here we assert the returned replay metadata.) +subdetailsok:{[] + doinit[subdcfg[]]; feedtrades[5]; / fresh log dir so rowcount is deterministic + sd:(tk`subdetails)[`;`]; + (use`di.pubsub)[`closesub][0]; / deregister the in-process handle-0 sub so later tests aren't polluted + all(5=sd`rowcount; + 2=count sd`tables; + all `trade`quote in sd`tables; + all `trade`quote in key sd`schemas; + 98h=type sd[`schemas]`trade; + sd[`logfile]~hsym`$BASE,"/subdlog/tp",string sd`date) + } diff --git a/di/proc/tickerplant/tickerplant.md b/di/proc/tickerplant/tickerplant.md new file mode 100644 index 00000000..73e549f3 --- /dev/null +++ b/di/proc/tickerplant/tickerplant.md @@ -0,0 +1,90 @@ +# di.proc.tickerplant + +The real-time capture root: receives updates from feeds, timestamps and logs them, +publishes to subscribers, and rolls the log at end of day. It depends on no other +process type, so it's the base of the RT stack (and what `di.subscriptions` / the RDB +will subscribe to). + +Classic TorQ splits kdb+tick's `u.q` into pure pubsub (`code/common/u.q`) and the +tick/log/EOD logic (inline in `code/processes/tickerplant.q`). This module is the +latter, orchestrating three hard dependencies — none of which use the +`init[config;deps]` convention, so di.proc.tickerplant initialises each in its own idiom: + +| Dependency | Source | Role | Init idiom | +| --- | --- | --- | --- | +| `di.pubsub` | kdbx-modules | subscribe / publish / EOD broadcast | `setsubtables[tabs]` then `init[]` | +| `di.tplogmgr` | TorqX | log open / replay / append / roll | `open[dir;date]` (no init) | +| `di.eodtime` | vendored (feature-eodtime) | roll timing, data-tz stamping | `init[merged dict]` | + +Injected deps (from `di.torq`): `log`, `timer`. (`handlers` is passed but unused — +`di.pubsub` installs its own `.z.pc` for subscriber cleanup; see Notes.) + +## Config + +```toml +publishmode = "immediate" # "immediate" (publish each update) or "batched" (buffer, flush on a timer) +pubperiod = 1 # batched only: flush period in SECONDS (di.timer granularity) +tplogdir = "tplog" # relative to TORQXDATAHOME, or absolute; empty/absent = no logging +schemafile = "database.q" # defaults to /database.q (schema is code, not data) +# rolltimezone / datatimezone / rolltimeoffset -> passed to di.eodtime (default GMT/GMT/0) +``` + +## Behaviour + +- **Schema**: loads `schemafile` at root; the publishable tables are the **unkeyed** + ones with `time`,`sym` as their first two columns (so ambient/system root tables are + ignored — a clean di.torq process has only the schema tables at root anyway). `` `g# `` + is applied to each `sym`. A schema yielding no publishable table is an error. +- **Feed entry** (`upd`, also `.u.upd`, published at root for IPC): timestamps the + data with `.z.p + di.eodtime.getdailyadj[]` unless the first column is already a + timestamp (so replay is idempotent); writes `(`upd;t;x)` to the log; then **immediate** + → `di.pubsub.publish` straight away, or **batched** → `t insert` into the buffer for + the flush job. +- **Subscriber entry** (`.u.sub[tabs;syms]`, published at root): delegates to + `di.pubsub.subscribe` (syms=` → all data; a sym list → sym-filtered). +- **Timer jobs** (via injected `di.timer`): an EOD-roll check every second; plus, in + batched mode, a flush every `pubperiod` seconds (`di.pubsub.pubclear`). +- **End of day** (`endofday`, published at root; fired by the roll-check job or via + IPC): flush any buffer, `di.pubsub.callendofday`, roll the log + (`di.tplogmgr.roll`), and advance di.eodtime's date / next-roll / daily-adjustment. +- **Restart**: `di.tplogmgr.open` replays the day's log through the root `upd`, restoring + in-memory state (batched) and the message count. + +## Startup order note + +The root `upd`/`.u.sub`/`endofday` names are published **before** the log is opened, +because `di.tplogmgr.open` replays via `-11!`, which executes the root-level `upd`. + +## Notes / known gaps + +- `di.pubsub` sets its own global `.z.pc` for subscriber cleanup, bypassing `di.torq.handlers`. + Fine in a TP process (nothing else claims `.z.pc` there); if client tracking is ever + added to a TP, `di.pubsub` should register through `di.torq.handlers` upstream instead. +- A single malformed schema table (missing `time`/`sym`) is silently skipped rather + than erroring (shape-filtering trade-off vs TorQ's strict assertion, chosen for + robustness against ambient root tables). +- Batched flush granularity is whole seconds (di.timer's period unit); TorQ's `system"t"` + allows sub-second. Fine for v1. +- `di.eodtime` is vendored from an unmerged PR and `rolltimeoffset` can't be expressed + in TOML (no timespan type) — GMT-midnight rolls need no offset; a non-default offset + needs a `.q` settings file for now. + +## Testing + +`test.csv`/`test.q` (k4unit) use the **real** pubsub/tplog/eodtime with a mock +log/timer, covering: schema shape-validation (a no-time/sym schema fails init), +immediate mode (no local retention + log write), batched mode (buffer then flush +clears), the scheduled timer jobs, log replay restoring the buffer on restart, feeding +with logging disabled, and an EOD roll opening the next day's log. Real +feed→TP→subscriber **delivery** and the forced roll are proven in the TorqX-POC +end-to-end (a synchronous k4unit test can't flush pubsub's async `-25!` sends). Run: + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.proc.tickerplant +``` + +End-to-end (TorqX-POC): `torqx.sh start tickerplant1`, then a subscriber +(`hopen`, `.u.sub[`;`]`) and a feed (`.u.upd`) — verified: 3 fed trades reach the +subscriber, the tp log holds 3 messages and replays 3 on restart, and a forced +`endofday` rolls to the next day's log. diff --git a/di/proc/tickerplant/tickerplant.q b/di/proc/tickerplant/tickerplant.q new file mode 100644 index 00000000..1343a22c --- /dev/null +++ b/di/proc/tickerplant/tickerplant.q @@ -0,0 +1,168 @@ +/ di.proc.tickerplant - real-time capture root. Orchestrates three hard deps in their own +/ init idioms (none use init[config;deps]): di.pubsub (sub/pub, kdbx-modules), di.tplogmgr +/ (log lifecycle, TorqX), di.eodtime (roll timing, vendored). Injected deps: log, timer. +/ Ported from the tick/log/EOD logic inline in TorQ/code/processes/tickerplant.q; the +/ pure pubsub half is di.pubsub. Both publish modes supported: `immediate (publish each +/ update straight away) and `batched (buffer per table, flush on a timer period). + +/ base dirs: CODE/CONFIG lives under TORQXAPPHOME, runtime DATA under TORQXDATAHOME (falls +/ back to TORQXAPPHOME when unset - fine for a sample app where they coincide). +apphome:{getenv[`TORQXAPPHOME]} +datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]} + +/ resolve a possibly-relative dir setting to an absolute path STRING under `base` (for tplog / +/ shell). handles symbol (.q settings) or string (.toml) input, and a leading handle colon. +resolvedir:{[base;dir] + dir:$[10h=abs type dir;dir;string dir]; + dir:$[(0type first x;a,x;(enlist(count first x)#a),x] + } + +/ feed entry point (published at root as `upd`/`.u.upd`, called by feeds over IPC). +/ stamps, logs (unless replaying - logh is 0 during the replay inside tplog.open), then +/ publishes immediately or buffers into the root table for the flush job. +upd:{[t;x] + x:stamp tocols x; + if[.z.m.logh>0;(.z.m.tp`write)[.z.m.logh;(`upd;t;x)];.z.m.msgcount+:1]; + $[.z.m.publishmode=`batched; + t insert x; + (.z.m.ps`publish)[t;flip (cols value t)!$[0>type first x;enlist each x;x]] + ]; + } + +/ subscriber entry point (published at root as `.u.sub`). syms=` -> all data for the +/ table(s); a sym list -> a sym-filtered subscription. Delegates to di.pubsub, whose +/ .z.w-based registration sees the calling subscriber's handle. +sub:{[tabs;syms] (.z.m.ps`subscribe)[tabs;syms]} + +/ subscription-details call (published at root as `.u.subdetails`) for a replaying +/ subscriber - di.proc.rdb via di.subscriptions. In ONE synchronous call it (a) registers the +/ calling handle for live updates via di.pubsub (keyed on .z.w) and (b) returns everything +/ needed to replay the pre-subscription history exactly once: +/ tables - the tables actually subscribed to +/ schemas - tablename!empty-schema dict, so the subscriber can define the tables +/ logfile - the current tp log file (` if logging disabled), for -11! replay +/ rowcount - messages logged AT SUBSCRIPTION TIME. The subscriber replays exactly this +/ many (di.tplogmgr.replayupto), so live messages arriving after subscription - +/ which are ALSO delivered over the feed - are not double-processed. Captured +/ in the same synchronous call as the subscribe, so no upd interleaves. +/ date - the log date +/ This is the clean single-call analogue of the segmented TP's `subdetails`, deliberately +/ NOT the classic standard-TP surface (.u.i/.u.L/.u.d global reads). +subdetails:{[tabs;syms] + sub:(.z.m.ps`subscribe)[tabs;syms]; + d:(.z.m.eod`getd)[]; + lf:$[00;r:(.z.m.tp`roll)[.z.m.logh;.z.m.tplogdir;d];.z.m.logh:r 0;.z.m.msgcount:r 1]; + (.z.m.eod`setd)[d+1]; + (.z.m.eod`setnextroll)[(.z.m.eod`getroll)[.z.p]]; + (.z.m.eod`setdailyadj)[(.z.m.eod`getdailyadjustment)[]]; + .z.m.log[`info][`tickerplant;"end of day complete, rolled ",(string d)," -> ",string d+1]; + } + +/ EOD check (timer job, ~1s): roll when the next-roll time has passed. +eodcheck:{[] if[(.z.m.eod`getnextroll)[]<.z.p;endofday[]];} + +/ builds eodtime's merged init dict from the log dep + any tz config present, coercing +/ timezone values to symbols. rolltimeoffset only passed if already a timespan (TOML has +/ no timespan type, so a .toml settings file leaves it at eodtime's default). +eoddeps:{[config;logdep] + d:enlist[`log]!enlist logdep; + if[`rolltimezone in key config;d[`rolltimezone]:astz config`rolltimezone]; + if[`datatimezone in key config;d[`datatimezone]:astz config`datatimezone]; + if[(`rolltimeoffset in key config) and -16h=type config`rolltimeoffset;d[`rolltimeoffset]:config`rolltimeoffset]; + d + } + +init:{[config;deps] + if[not `log in key deps;'"di.proc.tickerplant: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.proc.tickerplant: timer dependency is required - see di.timer"]; + .z.m.log:deps`log; + .z.m.timer:deps`timer; + .z.m.cfg:config; + .z.m.publishmode:$[`publishmode in key config;astz config`publishmode;`immediate]; + .z.m.pubperiod:$[`pubperiod in key config;"j"$config`pubperiod;1]; + .z.m.tplogdir:$[`tplogdir in key config;resolvedir[datahome[];config`tplogdir];""]; + + / schema: load the schema file at root; publishable tables are the UNKEYED ones with + / time,sym as their first two columns. Shape-filtering (rather than asserting every + / root table qualifies) keeps the TP robust to ambient root tables that aren't part of + / the schema - in a clean di.torq process root holds only the schema tables, but this + / avoids a sharp edge if anything else is defined at root. A schema that yields no + / publishable table is an error. Trade-off vs TorQ: a single malformed schema table is + / skipped rather than erroring - flagged in the docs. + schemafile:$[`schemafile in key config;resolvedir[apphome[];config`schemafile];apphome[],"/database.q"]; + system "l ",schemafile; + allt:tables[]; + tabs:allt where {(98h=type value x) and `time`sym~2#cols x} each allt; + if[0=count tabs;'"di.proc.tickerplant: schema file loaded no publishable tables (need unkeyed with time,sym as the first two columns): ",schemafile]; + {@[x;`sym;`g#]} each tabs; + .z.m.tables:tabs; + + / pubsub: set the subscribable table list, then build its schema state from root tables + .z.m.ps:use`di.pubsub; + (.z.m.ps`setsubtables)[tabs]; + (.z.m.ps`init)[]; + + / eodtime: single merged dict (log + tz config) + .z.m.eod:use`di.eodtime; + (.z.m.eod`init)[eoddeps[config;.z.m.log]]; + + / tplog: prepared now; log opened after the root upd is published (replay needs it) + .z.m.tp:use`di.tplogmgr; + .z.m.logh:0; + .z.m.msgcount:0; + + / publish the IPC surface at real root names (use mangles module code into a private + / namespace, so a remote/replayed `upd`/`.u.sub` must resolve at root). Done BEFORE + / opening the log so tplog.open's -11! replay finds `upd`. + set[`upd;upd]; + set[`.u.upd;upd]; + set[`.u.sub;sub]; + set[`.u.subdetails;subdetails]; + set[`endofday;endofday]; + set[`.u.end;endofday]; + + if[0 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) +``` + +The schema comes from the **tickerplant** (via `subdetails`), not a local `database.q` — +di.subscriptions defines the tables at root from what the TP returns. + +## Behaviour + +- **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. +- **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. +- **End of day** (`endofday[date]`, published at root, also `.u.end`): the tickerplant + broadcasts `(`endofday;date)` at roll (the same trigger as di.proc.rdb). di.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`. + +## RDB / WDB interaction + +When a wdb is present the rdb must run **`reloadenabled = true`** (see di.proc.rdb). At EOD: + +1. the tp broadcasts `(`endofday;date)` to **both**. The rdb snapshots its row counts and + escapes (keeping the prior day live+queryable); the wdb owns the writedown. +2. the wdb flushes → sorts → moves the partition into the hdb. +3. the wdb reloads in order: `.hdb.reload[]` on each hdb (it re-reads the new partition), then + `(`reload;date)` on each rdb (it `dropfirstnrows` — drops exactly the prior day it held, + keeping the new day's ticks). + +This split is also **why only one process writes `hdb/sym`**: with `reloadenabled=1b` the rdb +does not enumerate/save, so the wdb is the sole writer — no concurrent-`.Q.en` race. + +## Why a separate working dir + move (not write-straight-to-hdb) + +The `savedir` (default `wdb`, under `TORQXDATAHOME`) is the wdb's **permanent working +directory** — data passes through it transiently on its way to the hdb, but the directory +itself is used every day and is **not** a manually-created scratch dir to be cleaned up. (It is +deliberately named `wdb`, not `wdbtemp`, so it isn't mistaken for disposable.) + +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`. This is also why `di.dbwrite.savedown`/`appenddown` (which assume the +enumerate dir == the write dir) don't fit the write path — the create-or-append write is +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. +- **IDB tier** (`notifyidbs`/`idbreload`/`filldb`/`initmissingtables`). +- **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.proc.gateway not built). +- **FinSpace/AWS** and the `endofperiod` STP stub — stripped. + +## Module-namespace notes + +Root tables are **read** with bare `value t` (bare reads fall through to root) but **written** +and **cleared** via `@[`.;..]` — a bare write from a `use`-loaded module (or under `-11!` +replay) lands in the module's private namespace. The replay `upd` is therefore root-safe. + +## 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 +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). + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.proc.wdb +``` diff --git a/di/proc/wdb/wdb.q b/di/proc/wdb/wdb.q new file mode 100644 index 00000000..70b1f3cc --- /dev/null +++ b/di/proc/wdb/wdb.q @@ -0,0 +1,230 @@ +/ di.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; the IDB tier +/ (notifyidbs/idbreload/filldb); compression. REMOVED (deprecated): finspace/aws and the +/ .z.pd tempfix guards; the endofperiod STP stub. +/ --- +/ 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) +assym:{[x] $[11h=abs type x;x;`$x]} +aslist:{[x] $[0>type x;enlist x;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. +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). +apphome:{getenv[`TORQXAPPHOME]} +datahome:{$[count h:getenv[`TORQXDATAHOME];h;getenv[`TORQXAPPHOME]]} + +/ resolve 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) +savetodisk:{[] flushtable[.z.m.immediate;] each tablelist[];} + +/ 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. +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:{[date;t] + dir:` sv (.Q.par[.z.m.savedir;date;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:{[date] + src:.Q.par[.z.m.savedir;date;`]; + if[not count key src;.z.m.log[`warn][`wdb;"no working partition to move for ",string date];:()]; + dst:.Q.par[.z.m.hdbdir;date;`]; + 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.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; + } + +/ tell every hdb of these types to reload (pick up the just-moved partition) +reloadhdbs:{[date] + 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; + } + +/ tell every rdb of these types to reload[date] (drop the prior day it was holding in memory). +/ async - the rdb's root reload[date] does the dropfirstnrows (see di.proc.rdb, reloadenabled=1b). +reloadrdbs:{[date] + h:raze {exec w from (.z.m.svc`getservers)[x]} each .z.m.rdbtypes; + {[wh;date] @[neg wh;(`reload;date);{[e] .z.m.log[`error][`wdb;"rdb reload send failed: ",e]}]}[;date] 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. +doreload:{[date] + informgateway[`reloadstart]; + {[date;pt] $[pt in .z.m.hdbtypes;reloadhdbs[date];pt in .z.m.rdbtypes;reloadrdbs[date];.z.m.log[`warn][`wdb;"reloadorder entry ",(string pt)," is neither an hdb nor rdb type - skipped"]]}[date;] each .z.m.reloadorder; + informgateway[`reloadend]; + } + +/ end of day: called by the tickerplant as endofday[date] (di.pubsub's dated broadcast, same +/ trigger as di.proc.rdb). Flush what remains, sort each working partition, move it into the hdb, then +/ reload downstream. Advance the partition for the new day. +endofday:{[date] + .z.m.log[`info][`wdb;"end of day for partition ",string date]; + flushtable[1b;] each tablelist[]; / flush all remaining rows + st:tablelist[]; + sortpart[date] each st; + movetohdb[date]; + doreload[date]; + .z.m.currentpartition:date+1; + .z.m.log[`info][`wdb;"end of day complete, wrote+moved: ",(", " sv string st)]; + } + +init:{[config;deps] + if[not `log in key deps;'"di.proc.wdb: log dependency is required - see di.util.log"]; + if[not `timer in key deps;'"di.proc.wdb: timer dependency is required - see di.timer"]; + if[not `servers in key deps;'"di.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.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.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.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[]; + + / 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]]]; + + / 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. + .z.m.svc:deps`servers; + sconfig:config,(enlist`connections)!enlist distinct .z.m.tptypes,.z.m.hdbtypes,.z.m.rdbtypes,.z.m.gatewaytypes; + (.z.m.svc`startup)[sconfig]; + + / install the flushing replay upd at root BEFORE subscribing, so the -11! replay driven by + / di.subscriptions flushes to disk as it goes (bounded memory). Swapped to updfn after. + @[`.;`upd;:;replayupd]; + + / block until a tickerplant is up, then subscribe (subdetails + replay) + tpt:first .z.m.tptypes; + if[not (.z.m.svc`waitfortype)[tpt;timeout;500]; + '"di.proc.wdb: no ",(string tpt)," connection within ",(string timeout),"ms - cannot start wdb"]; + tph:(.z.m.svc`gethandlebytype)[tpt;`any]; + .z.m.subs:use`di.subscriptions; + (.z.m.subs`init)[config;deps]; + sd:(.z.m.subs`subscribe)[tph;subscribeto;subscribesyms;replaylog]; + if[not sd[`date]~.z.m.currentpartition; + .z.m.log[`warn][`wdb;"tp log date ",(string sd`date)," != partition ",(string .z.m.currentpartition),"; using log date (cross-date working-dir move is deferred - see wdb.md)"]; + .z.m.currentpartition:sd`date]; + .z.m.log[`info][`wdb;"subscribed; replayed ",(string sd`rowcount)," message(s), partition date ",string sd`date]; + + / swap to the live accumulate upd (the timer flushes over-threshold), publish EOD entries + @[`.;`upd;:;updfn]; + @[`.;`endofday;:;endofday]; + @[`.;`.u.end;:;endofday]; + + / 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"]; + } diff --git a/di/pubsub/VERSION b/di/pubsub/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/pubsub/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/pubsub/init.q b/di/pubsub/init.q index fc3ad51c..35609995 100644 --- a/di/pubsub/init.q +++ b/di/pubsub/init.q @@ -1,3 +1,8 @@ \l ::pubsub.q -export:([subscribe;subscribestr;subscribestrfilter;publish;setsubtables;callendofperiod;callendofday;closesub;pubclear;init]) +/ module version, read from the on-disk VERSION file (the module-local `:::` path convention). +/ di.proc.tickerplant's deps.toml declares di.pubsub, so di.torq.depcheck needs BOTH the file +/ (pre-load manifest walk) and this export (post-load session audit). +version:first read0`:::VERSION + +export:([subscribe;subscribestr;subscribestrfilter;publish;setsubtables;callendofperiod;callendofday;closesub;pubclear;init;version]) diff --git a/di/serverselect/VERSION b/di/serverselect/VERSION new file mode 100644 index 00000000..6e8bf73a --- /dev/null +++ b/di/serverselect/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/di/serverselect/init.q b/di/serverselect/init.q new file mode 100644 index 00000000..81e48771 --- /dev/null +++ b/di/serverselect/init.q @@ -0,0 +1,19 @@ +\l ::serverselect.q + +/ logging is an injected dependency: the start-up script that wires the modules together - +/ or the user at run time - must call init with a required `log dependency before using the +/ module. kx.log is intentionally NOT loaded here. +/ note: the injected log dict must already be binary `info`warn`error!{[c;m]} - no adaptation +/ is done here; init fans it out into .z.m.loginfo/.z.m.logwarn/.z.m.logerr, called as +/ .z.m.loginfo[`ctx;"msg"] + +/ module version, read from the on-disk VERSION file (the module-local `:::` path convention). +/ di.torq.depcheck needs BOTH: the file, for its pre-load manifest walk (reads VERSION without +/ loading the module), and this export, for its post-load session audit of a loaded peer that a +/ manifest declares - di.proc.gateway's deps.toml declares di.serverselect, so a missing version +/ here fails a real gateway startup. +version:first read0`:::VERSION + +export:([init; + addserverfull;addserverattr;addserver;setserveractive;getserverstable;addserversfromtable; + getservers;selector;getserverbytype;gethandlebytype;gethpbytype;getserverids;version]) diff --git a/di/serverselect/integration.q b/di/serverselect/integration.q new file mode 100644 index 00000000..6e4ace17 --- /dev/null +++ b/di/serverselect/integration.q @@ -0,0 +1,277 @@ +/ =========================================================================== +/ di.serverselect integration test (real processes) +/ Spawns child q listeners, opens REAL IPC handles to them, and drives every +/ exported function through a realistic gateway lifecycle - register -> +/ query -> select -> route a live query to the chosen handle -> bulk-register +/ -> disconnect -> error handling -> init. Unlike a simulated test, the +/ selection functions hand back handles that are actually queried, so the +/ assertions prove queries reach the expected backend process. +/ . +/ Self-contained: no helper files. The child backends are bare `q` listeners +/ whose identity (`whoami`) and `ping` api are injected over IPC at setup; the +/ test launches and tears them down itself. +/ . +/ Requirements: +/ - run THIS script with KDB-X q (needs `use`) +/ - a q on PATH (override with $QBIN) to launch the child listeners +/ - some free TCP ports: the test scans for free ports from a pid-derived +/ base (so concurrent runs don't collide); set $SSPORT to pin the base +/ Run (QPATH must include this repo and the kx module dir): +/ QPATH=/path/to/kx/mod:/path/to/kdbx-modules /q integration.q +/ Exits with a non-zero code equal to the number of failed assertions. +/ =========================================================================== + +srvsel:use`di.serverselect; + +/ ---- tiny assertion harness ---- +/ note: avoid `desc`/`exp`/`log` as names - they are reserved words in KDB-X +PASS:0; FAIL:0; +lbl:{[ok] $[ok;" ok | ";" FAIL | "]}; +chk:{[nm;got;expd] + ok:got~expd; + $[ok;PASS+:1;FAIL+:1]; + m:lbl[ok],nm; + if[not ok; m:m," || got=",(.Q.s1 got)," exp=",.Q.s1 expd]; + -1 m; + }; +errtok:`$"__ERRORED__"; +chkerr:{[nm;f] + r:@[f;();{[e](errtok;e)}]; + ok:(0count free; + '"could not find ",string[n]," free ports scanning up from ",string start]; + :n#free; + }; +ports:findfree[baseport;count names]; + +launch:{[port] + / start a bare q listener detached and capture its shell background pid ($!) - so every + / child can be reaped by exact pid later, whether or not we ever connect to it, and with + / no dependence on the qbin path (identity/api are injected over IPC once connected) + :"I"$first system qbin," -p ",string[port]," -q /dev/null 2>&1 & echo $!"; + }; + +connect:{[port] + / open a handle, retrying for up to ~10s while the child binds and accepts + hp:`$":localhost:",string port; + step:{[hp;h] if[not null h; :h]; system"sleep 0.2"; @[hopen;(hp;500);{0Ni}]}[hp]; + :50 step/ 0Ni; + }; + +teardown:{[] + / always-run cleanup. kill every launched child by its captured pid (exact). the pkill + / fallback is a last resort for the rare case a pid was never captured - keyed on our own + / unique port and -q flag (NOT the qbin path, which is configurable), so a custom qbin + / cannot break it. the [-]p bracket keeps the pattern from matching this very kill command. + live:pids where not null pids; + if[count live; @[system;"kill ",(" " sv string live)," 2>/dev/null; true";{}]]; + {@[system;"pkill -f \"[-]p ",string[x]," -q\" 2>/dev/null; true";{}]} each ports; + @[hclose;;{}] each handles where not null handles; + }; + +/ launch the fleet (capturing each child's shell pid for exact-pid teardown), then connect +-1 "selected free ports: ",.Q.s1 ports; +pids:launch each ports; +handles:connect each ports; +/ guarantee the fleet is reaped on ANY exit (normal, error-abort, or exit code) +.z.exit:{teardown[]}; +if[any null handles; + -2 "failed to connect to child processes on ports: ",(" " sv string ports where null handles); + exit 3]; +/ inject each backend's identity + ping api over IPC +{[h;nm] h "whoami:`",string nm; h "ping:{whoami}";}'[handles;names]; +-1 "spawned ",(string count handles)," backend processes; real handles: ",.Q.s1 handles; + +/ route: select a server of type t via strategy sel, then SEND ping[] over the chosen handle +route:{[t;sel] h:srvsel.gethandlebytype[t;sel]; $[()~h; `NONE; h "ping[]"]}; +/ map serverids -> their handles (to route attribute-path selections) +sidhandles:{[sids] exec handle from srvsel.getserverstable[] where serverid in sids}; +/ the gateway's host/port for the hpup column - its real (dynamically chosen) address +gwhp:`$":localhost:",string ports 4; + +/ test steps run at top level (a single enclosing function would exceed q's +/ per-function constant limit). chk/chkerr trap their own assertion failures; +/ .z.exit guarantees teardown regardless of how the script ends. + +/ init must be called before use (log is a required injected dependency, no default) +srvsel.init[enlist[`log]!enlist `info`warn`error!({[c;m]};{[c;m]};{[c;m]})]; + +/ ========================================================================= +hdr"STEP 1 initial empty state"; +chk["fresh module: server table empty";0=count srvsel.getserverstable[];1b]; +chk["schema columns correct";`serverid`handle`procname`servertype`hpup`active`lastp`hits`attributes;cols srvsel.getserverstable[]]; + +/ ========================================================================= +hdr"STEP 2 registration of live handles (addserver / addserverattr / addserverfull)"; +srvsel.addserver[handles 0;`rdb]; +srvsel.addserver[handles 1;`rdb]; +srvsel.addserverattr[handles 2;`hdb;`date`sym!((d1;d2);`A`B)]; +srvsel.addserverattr[handles 3;`hdb;`date`sym!((d2;d3);`B`C)]; +srvsel.addserverfull[handles 4;`gw1;`gateway;gwhp;(enlist`region)!enlist`EU]; +chk["five servers registered";5=count srvsel.getserverstable[];1b]; +chk["serverids autoincrement 1..5";1 2 3 4 5i;exec serverid from srvsel.getserverstable[]]; +chk["handles stored are the real open handles";handles til 5;exec handle from srvsel.getserverstable[]]; +chk["servertypes as registered";`rdb`rdb`hdb`hdb`gateway;exec servertype from srvsel.getserverstable[]]; +chk["addserverfull populated procname";`gw1;first exec procname from srvsel.getserverstable[] where servertype=`gateway]; +chk["addserverfull populated hpup";gwhp;first exec hpup from srvsel.getserverstable[] where servertype=`gateway]; +chk["addserver -> empty attributes";(()!());first exec attributes from srvsel.getserverstable[] where handle=handles 0]; +chk["all active by default";1b;all exec active from srvsel.getserverstable[]]; + +/ ========================================================================= +hdr"STEP 3 getservers (lookup + attribute match scoring)"; +chk["lookups=` returns all active";5;count srvsel.getservers[`;`;()!()]]; +chk["servertype=hdb returns 2";2;count srvsel.getservers[`servertype;`hdb;()!()]]; +chk["servertype list rdb,hdb returns 4";4;count srvsel.getservers[`servertype;`rdb`hdb;()!()]]; +chk["procname=gw1 returns the gateway handle";enlist handles 4;exec handle from srvsel.getservers[`procname;`gw1;()!()]]; +chk["unknown servertype returns empty";0;count srvsel.getservers[`servertype;`nope;()!()]]; +chk["attribmatch column present";1b;`attribmatch in cols srvsel.getservers[`;`;()!()]]; +chk["complete date match flagged for some hdb on d1";1b; + any {x[`date]0} each (srvsel.getservers[`servertype;`hdb;(enlist`date)!enlist enlist d1])`attribmatch]; + +/ ========================================================================= +hdr"STEP 4 selector (strategies on a known table)"; +seltab:([]serverid:101 102 103i;handle:201 202 203i;lastp:(2024.01.03D0;2024.01.01D0;2024.01.02D0)); +chk["roundrobin picks oldest lastp";202i;(srvsel.selector[seltab;`roundrobin])`handle]; +chk["last picks newest lastp";201i;(srvsel.selector[seltab;`last])`handle]; +chk["any picks a row from the table";1b;((srvsel.selector[seltab;`any])`handle) in 201 202 203i]; +empt:([]serverid:`int$();handle:`int$();lastp:`timestamp$()); +chk["empty table -> null handle";0Ni;(srvsel.selector[empt;`roundrobin])`handle]; + +/ ========================================================================= +hdr"STEP 5 live routing (gethandlebytype / gethpbytype / getserverbytype)"; +/ round-robin across the two live rdbs: both start with null lastp, so LRU +/ visits rdb1, rdb2, rdb1, rdb2 - and each query is answered by that process +resp:{[i] route[`rdb;`roundrobin]} each til 4; +chk["round-robin routes to live rdbs in LRU order";`rdb1`rdb2`rdb1`rdb2;resp]; +chk["only the two live rdbs ever answer";`rdb1`rdb2;asc distinct resp]; +chk["gethpbytype gateway returns its hpup";gwhp;srvsel.gethpbytype[`gateway;`roundrobin]]; +chk["getserverbytype returns requested column";`gw1;srvsel.getserverbytype[`gateway;`procname;`roundrobin]]; +chk["gethandlebytype unknown type -> ()";();srvsel.gethandlebytype[`nope;`roundrobin]]; +chk["a single hdb query is answered by an hdb";1b;(route[`hdb;`roundrobin]) in `hdb1`hdb2]; +hitsbefore:exec sum hits from srvsel.getserverstable[] where servertype=`gateway; +srvsel.gethandlebytype[`gateway;`roundrobin]; +chk["selection increments hits";1b;(hitsbefore+1)=exec sum hits from srvsel.getserverstable[] where servertype=`gateway]; + +/ ========================================================================= +hdr"STEP 6 getserverids - servertype (symbol) path"; +chk["rdb -> the two rdb serverids";1 2i;asc raze srvsel.getserverids[`rdb]]; +chk["rdb,hdb -> all four serverids";1 2 3 4i;asc raze srvsel.getserverids[`rdb`hdb]]; +srvsel.setserveractive[handles 0;0b]; srvsel.setserveractive[handles 1;0b]; +chkerr["all requested servertype inactive -> error";{srvsel.getserverids[`rdb]}]; +srvsel.setserveractive[handles 0;1b]; srvsel.setserveractive[handles 1;1b]; + +/ ========================================================================= +hdr"STEP 7 getserverids - attribute path + routing to the matched backend"; +/ hdb1 covers (d1,d2)/(A,B); hdb2 covers (d2,d3)/(B,C) +chk["date=d1 -> hdb1 only";enlist`hdb1; + distinct {x"ping[]"} each sidhandles raze srvsel.getserverids[enlist[`date]!enlist enlist d1]]; +chk["cross (d1,d2)x(A,B) -> hdb1 alone covers it";enlist`hdb1; + distinct {x"ping[]"} each sidhandles raze srvsel.getserverids[`date`sym!((d1;d2);`A`B)]]; +chk["independent over d1,d2,d3 + A,B,C -> both hdbs contribute";`hdb1`hdb2; + asc distinct {x"ping[]"} each sidhandles raze srvsel.getserverids[`date`sym`attributetype!((d1;d2;d3);`A`B`C;`independent)]]; +chk["servertype key scopes attribute filter to hdbs";3 4i;asc raze srvsel.getserverids[`servertype`date!(`hdb;enlist d2)]]; +chk["empty requirement dict -> all active serverids";1 2 3 4 5i;asc raze srvsel.getserverids[()!()]]; +chkerr["besteffort=0b impossible -> error";{srvsel.getserverids[`date`besteffort!(enlist 2099.01.01;0b)]}]; +chkerr["no server has requested attribute value -> error";{srvsel.getserverids[enlist[`date]!enlist enlist 2099.01.01]}]; + +/ ========================================================================= +hdr"STEP 8 addserversfromtable (bulk registration of live handles)"; +conntab:([]w:handles 5 6;proctype:`rdb`hdb;attributes:(()!();`date`sym!((d1;d3);`A`C))); +srvsel.addserversfromtable[`rdb`hdb;conntab]; +chk["bulk-registered handles 5,6 now present";2=count select from srvsel.getserverstable[] where handle in handles 5 6;1b]; +chk["bulk-registered rdb3 is reachable via its handle";`rdb3;(handles 5)"ping[]"]; +chk["bulk-registered rdb3 now appears in rdb serverids";1b;6i in raze srvsel.getserverids[`rdb]]; +/ skip-already-active: re-offering a live handle must not duplicate it +n0:count srvsel.getserverstable[]; +srvsel.addserversfromtable[`rdb;([]w:enlist handles 0;proctype:enlist`rdb;attributes:enlist()!())]; +chk["already-active handle skipped (no new row)";n0;count srvsel.getserverstable[]]; +/ (proctype filter, `ALL, and optional procname/hpup columns are covered in test.csv) + +/ ========================================================================= +hdr"STEP 9 disconnect: kill a backend, deactivate it, prove routing adapts"; +/ a real gateway's .z.pc handler would call setserveractive[h;0b] on the dropped handle +/ guard: the kill is only a genuine test if rdb1's pid was captured. if pids 0 were null, +/ string 0Ni -> "0Ni" and the kill silently no-ops, degrading STEP 9 into a deactivation-only +/ test. fail loudly here rather than pass on a half-exercised path. +chk["rdb1 pid captured (so the kill below is real)";1b;not null pids 0]; +@[system;"kill ",string[pids 0]," 2>/dev/null; true";{}]; system"sleep 0.3"; +srvsel.setserveractive[handles 0;0b]; +/ active rdbs are now rdb2 (live) and rdb3 (live); the dead rdb1 must never be picked +postresp:{[i] route[`rdb;`roundrobin]} each til 6; +chk["killed/deactivated rdb1 is never selected";1b;not `rdb1 in postresp]; +chk["no routed query hits a dead handle (all answered)";1b;not `NONE in postresp]; +chk["the two remaining live rdbs both serve";`rdb2`rdb3;asc distinct postresp]; + +/ ========================================================================= +hdr"STEP 10 error handling (every guarded path signals + logs)"; +chkerr["addserverfull rejects non-int handle";{srvsel.addserverfull[`bad;`;`rdb;`;()!()]}]; +chkerr["addserverfull rejects non-symbol servertype";{srvsel.addserverfull[71i;`;"rdb";`;()!()]}]; +chkerr["addserver rejects bad handle";{srvsel.addserver[`bad;`rdb]}]; +chkerr["addserverattr rejects bad servertype";{srvsel.addserverattr[73i;"hdb";()!()]}]; +chkerr["setserveractive rejects non-int handle";{srvsel.setserveractive["bad";0b]}]; +chkerr["setserveractive rejects non-boolean flag";{srvsel.setserveractive[1i;`yes]}]; +chkerr["getservers rejects bad nameortype";{srvsel.getservers[`badname;`x;()!()]}]; +chkerr["selector rejects unknown strategy";{srvsel.selector[seltab;`bogus]}]; +chkerr["getserverids rejects null servertype";{srvsel.getserverids[`]}]; +chkerr["getserverids rejects unregistered servertype";{srvsel.getserverids[`nope]}]; +chkerr["getserverids rejects non-symbol non-dict arg";{srvsel.getserverids[42]}]; +chkerr["getserverids rejects nested/malformed attribute value";{srvsel.getserverids[(enlist`date)!enlist enlist d1,d2]}]; +chkerr["addserversfromtable rejects missing columns";{srvsel.addserversfromtable[`rdb;([]x:enlist 1i)]}]; + +/ ========================================================================= +hdr"STEP 11 init (required log dependency - bespoke + kx.log)"; +caplog:([]lvl:`symbol$();msg:()); +caplogger:`info`warn`error!({[c;m]`caplog upsert(`info;m)};{[c;m]`caplog upsert(`warn;m)};{[c;m]`caplog upsert(`error;m)}); +srvsel.init[enlist[`log]!enlist caplogger]; +caplog:0#caplog; +srvsel.addserver[40i;`rdb]; +chk["injected logger captures an info message";1b;0type deps; + '"di.serverselect: deps must be a dict with `log key"]; + if[not `log in key deps; + '"di.serverselect: log dependency is required; pass `info`warn`error functions keyed on `log"]; + if[99h<>type deps`log; + '"di.serverselect: log value must be a dict; pass `info`warn`error functions"]; + if[not all (`info`warn`error) in key deps`log; + '"di.serverselect: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + .z.m.loginfo:deps[`log]`info; + .z.m.logwarn:deps[`log]`warn; + .z.m.logerr:deps[`log]`error; + }; + +nextserverid:{ + / internal - increment and return the next unique server ID + .z.m.serverid:serverid+1i; + :.z.m.serverid; + }; + +updatestats:{[sid] + / internal - update last-access timestamp and hit count for a single server + / keyed on serverid (unique) rather than handle, which may be shared by multiple servers + .z.m.servers:update lastp:.z.p,hits:hits+1i from servers where serverid=sid; + }; + +addserverfull:{[h;pname;st;hp;att] + / register a server with full details: handle, procname, servertype, hpup and attribute dictionary + if[not -6h=type h;.z.m.logerr[`addserverfull;err:"di.serverselect: handle must be an int; got type ",string type h];'err]; + if[not -11h=type st;.z.m.logerr[`addserverfull;err:"di.serverselect: servertype must be a symbol; got type ",string type st];'err]; + .z.m.loginfo[`addserverfull;"registering server: handle=",(string h),", procname=",string[pname],", type=",string st]; + .z.m.servers:servers upsert (nextserverid[];h;pname;st;hp;1b;0Np;0i;att); + }; + +addserverattr:{[h;st;att] + / register a server with servertype and attributes; procname and hpup default to null + addserverfull[h;`;st;`;att]; + }; + +addserver:{[h;st] + / register a server with no attributes; procname and hpup default to null + addserverfull[h;`;st;`;()!()]; + }; + +setserveractive:{[h;a] + / mark a registered server active (1b) or inactive (0b); called on connect and disconnect + if[not -6h=type h;.z.m.logerr[`setserveractive;err:"di.serverselect: handle must be an int; got type ",string type h];'err]; + if[not -1h=type a;.z.m.logerr[`setserveractive;err:"di.serverselect: active flag must be a boolean; got type ",string type a];'err]; + .z.m.loginfo[`setserveractive;"marking handle=",(string h)," active=",string a]; + .z.m.servers:update active:a from servers where handle=h; + }; + +getserverstable:{[] + / return the current registered server table + :servers; + }; + +addserversfromtable:{[proctypes;conntable] + / register active servers from a connection table filtered by proctype + / conntable must have columns: w (int handle), proctype (symbol), attributes (dict per row) + / optional columns: procname (symbol), hpup (symbol) - populated from conntable if present + / pass proctypes:`ALL to register all process types + if[not all `w`proctype`attributes in cols conntable; + .z.m.logerr[`addserversfromtable;err:"di.serverselect: conntable must have columns w, proctype and attributes; got: ",", " sv string cols conntable]; + 'err; + ]; + activehandles:(0i;0Ni),exec handle from servers where active; + rows:select from conntable where + ((proctype in proctypes) or proctypes~`ALL), + not w in activehandles; + .z.m.loginfo[`addserversfromtable;"registering ",(string count rows)," servers from connection table"]; + pnames:$[`procname in cols rows; rows`procname; count[rows]#`]; + hpups:$[`hpup in cols rows; rows`hpup; count[rows]#`]; + addserverfull'[rows`w;pnames;rows`proctype;hpups;rows`attributes]; + }; + +attributematch:{[req;avail] + / compute match result for each key in req against what avail advertises + / returns dict of attrname!(complete_match_bool;matched_values) for each required attribute key + / keys present in req but absent in avail return (0b;()) + vals:key[req] inter key avail; + notpresent:noval!(count noval:key[req] except key avail)#enlist(0b;()); + :notpresent,vals!{($[0>type y;x~y;all x in y];(x,()) inter y,())}'[req vals;avail vals]; + }; + +getservers:{[nameortype;lookups;req] + / look up active servers by servertype or procname with per-attribute match scoring + / nameortype: `servertype or `procname; pass ` as lookups to return all active servers + / req: attribute requirements dict - use ()!() for no attribute filtering + / returns table with attribmatch column showing (complete_bool;matched_values) per attribute key + if[(not `~lookups) and not nameortype in `servertype`procname; + .z.m.logerr[`getservers;err:"di.serverselect: nameortype must be `servertype or `procname; got: ",string nameortype]; + 'err; + ]; + r:$[`~lookups; + select serverid,procname,servertype,hpup,handle,lastp,attributes from servers where active; + nameortype~`servertype; + select serverid,procname,servertype,hpup,handle,lastp,attributes from servers where active,servertype in lookups; + select serverid,procname,servertype,hpup,handle,lastp,attributes from servers where active,procname in lookups]; + if[0=count r;:update attribmatch:attributes from r]; + am:attributematch[req] each r`attributes; + :update attribmatch:am from r; + }; + +selector:{[servertable;selection] + / pick one row from servertable using the given strategy + / selection: `roundrobin (least recently used), `any (random), `last (most recently used) + if[not selection in `roundrobin`any`last; + .z.m.logerr[`selector;err:"di.serverselect: unknown selection strategy: ",string selection]; + 'err; + ]; + :$[selection=`roundrobin; first `lastp xasc servertable; + selection=`any; rand servertable; + last `lastp xasc servertable]; + }; + +getserverbytype:{[ptype;serverval;selection] + / return a single server attribute value for a servertype using the given selection strategy + / ptype: servertype symbol; serverval: column to return e.g. `handle or `hpup; selection: `roundrobin`any`last + r:getservers[`servertype;ptype;()!()]; + if[not count r;:()]; + r:selector[r;selection]; + updatestats[r`serverid]; + :r serverval; + }; + +gethandlebytype:getserverbytype[;`handle;]; +gethpbytype:getserverbytype[;`hpup;]; + +getserverids:{[att] + / return server IDs matching a servertype list or attribute requirement dictionary + / att: symbol list of servertypes, or dict of attribute requirements (optionally keyed on `servertype) + / dispatch the symbol-list path to getserveridsbytype and the dict path to getserveridstype + if[99h<>type att; :getserveridsbytype att]; + / validate attribute-requirement values are atoms or simple vectors (control keys excepted); + / a nested/general-list value (type 0h) would otherwise crash the cross matcher with a raw 'type + reqkeys:key[att] except `servertype`attributetype`besteffort; + if[count badkeys:reqkeys where 0h=type each att reqkeys; + .z.m.logerr[`getserverids;err:"di.serverselect: attribute requirement values must be atoms or simple vectors; nested/mixed for: ",", " sv string badkeys]; + 'err]; + serverids:$[`servertype in key att; + raze getserveridstype[delete servertype from att] each (),att`servertype; + getserveridstype[att;`all]]; + if[all 0=count each serverids; + .z.m.logerr[`getserverids;err:"di.serverselect: no servers match requested attributes"]; + 'err; + ]; + :serverids; + }; + +getserveridsbytype:{[att] + / internal - resolve server IDs for a servertype symbol or symbol list + / validates each requested type is registered and currently active + if[not 11h=abs type att; + .z.m.logerr[`getserveridsbytype;err:"di.serverselect: servertype must be a symbol list (11h) or attribute dict (99h)"]; + 'err; + ]; + servertype:distinct att,(); + activeservers:exec distinct servertype from servers where active; + allservers:exec distinct servertype from servers; + activeserversmsg:". available servers: ",", " sv string activeservers; + if[any null att; + .z.m.logerr[`getserveridsbytype;err:"di.serverselect: null servertype passed as argument",activeserversmsg]; + 'err; + ]; + if[count servertype except activeservers; + .z.m.logerr[`getserveridsbytype;err:"di.serverselect: ",$[max not servertype in allservers; + "not valid servers: ",", " sv string servertype except allservers; + "requested servers currently inactive: ",", " sv string servertype except activeservers + ],activeserversmsg]; + 'err; + ]; + :(exec serverid by servertype from servers where active)[servertype]; + }; + +getserveridstype:{[att;typ] + / internal - filter active servers by servertype and attribute requirements + / resolves besteffort and attributetype control keys then dispatches to cross or independent matching + besteffort:1b; + attype:`cross; + svrs:$[typ=`all; + exec serverid!attributes from servers where active; + exec serverid!attributes from servers where active,servertype=typ]; + if[`besteffort in key att; + if[-1h=type att`besteffort; besteffort:att`besteffort]; + att:delete besteffort from att; + ]; + if[`attributetype in key att; + if[-11h=type att`attributetype; attype:att`attributetype]; + att:delete attributetype from att; + ]; + res:$[attype=`independent; + getserversindependent[att;svrs;besteffort]; + getserverscross[att;svrs;besteffort]]; + serverids:first value flip $[99h=type res; key res; res]; + if[all 0=count each serverids; + .z.m.logerr[`getserveridstype;err:"di.serverselect: no servers match ",string[typ]," requested attributes"]; + 'err; + ]; + :serverids; + }; + +/ internal - build a cross product table from a nested dictionary +buildcross:{(cross/){flip (enlist y)#x}[x] each key x}; + +getserversinitial:{[req;att] + / internal - initial filter shared by cross and independent matching + / drops servers missing any required attribute key, ranks survivors by coverage + if[0=count req; :([]serverid:enlist key att)]; + att:(where all each (key req) in/: key each att)#att; + if[not count att;.z.m.logerr[`getserversinitial;err:"di.serverselect: no servers report all requested attributes"];'err]; + s:update serverid:key att from value req in'/: (key req)#/:att; + s:s idesc value min each sum each' `serverid xkey s; + s:`serverid xkey 0!(key req) xgroup s; + :s; + }; + +getserverscross:{[req;att;besteffort] + / internal - find servers satisfying the cross product of all attribute requirements + / each attribute combination must be coverable by a single server + if[0=count req; :([]serverid:enlist key att)]; + s:getserversinitial[req;att]; + reqcross:buildcross[req]; + / scan through each server group accumulating which cross-product rows have been covered + util:flip `remaining`found!flip ( + {[x;y;z] (y[0] except found; y[0] inter found:$[0=count y[0];y[0];buildcross x@'where each z])}[req]\ + )[(reqcross;());value s]; + if[(count last util`remaining) and not besteffort; + .z.m.logerr[`getserverscross;err:"di.serverselect: cannot satisfy query - cross product of all attributes cannot be matched"]; + 'err; + ]; + s:1!(0!s) w:where not 0=count each util`found; + :(key s)!distinct each' flip each util[w]`found; + }; + +getserversindependent:{[req;att;besteffort] + / internal - find servers satisfying attribute requirements independently + / each individual requirement only needs to be matched by one server + if[0=count req; :([]serverid:enlist key att)]; + s:getserversinitial[req;att]; + / mask out server groups whose contribution is already covered by earlier groups + filter:(value s)¬ -1 _ (0b&(value s) enlist 0),maxs value s; + alldone:1+first where all each all each' maxs value s; + if[(null alldone) and not besteffort; + .z.m.logerr[`getserversindependent;err:"di.serverselect: cannot satisfy query - not all attributes can be matched"]; + 'err; + ]; + s:1!(0!s) w:where any each any each' filter; + :(key s)!{(key x)!(value x)@'where each y key x}[req] each value s&filter w; + }; diff --git a/di/serverselect/test.csv b/di/serverselect/test.csv new file mode 100644 index 00000000..f92b617c --- /dev/null +++ b/di/serverselect/test.csv @@ -0,0 +1,194 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,srvsel:use`di.serverselect,1,1,load module +before,0,0,q,"noop:`info`warn`error!({[c;m]};{[c;m]};{[c;m]})",1,1,define a no-op binary logger {[c;m]} +before,0,0,q,srvsel.init[enlist[`log]!enlist noop],1,1,init the module with the required log dependency before use + +/ ---- getserverstable: initial state ---- +comment,,,,,,,getserverstable - initial state before any addserverattr +true,0,0,q,0=count srvsel.getserverstable[],1,1,servers empty on fresh module load +true,0,0,q,`serverid`handle`procname`servertype`hpup`active`lastp`hits`attributes~cols srvsel.getserverstable[],1,1,servers has correct schema + +/ ---- addserverattr / addserver / addserverfull: registration ---- +comment,,,,,,,addserverattr and addserver - server registration +run,0,0,q,srvsel.addserver[1i;`rdb],1,1,register rdb server with no attributes +run,0,0,q,srvsel.addserver[2i;`rdb],1,1,register second rdb server +run,0,0,q,"srvsel.addserverattr[3i;`hdb;`date`sym!(2024.01.01 2024.01.02;`AAPL`MSFT)]",1,1,register hdb server with date and sym attributes +true,0,0,q,3=count srvsel.getserverstable[],1,1,three servers registered +true,0,0,q,all exec active from srvsel.getserverstable[],1,1,all registered servers are active by default +true,0,0,q,`rdb`rdb`hdb~exec servertype from srvsel.getserverstable[],1,1,servertypes match registered order +true,0,0,q,(1i;2i;3i)~exec handle from srvsel.getserverstable[],1,1,handles match registered order +true,0,0,q,1 2 3i~exec serverid from srvsel.getserverstable[],1,1,server IDs autoincrement from 1 +true,0,0,q,all null exec procname from srvsel.getserverstable[],1,1,procname is null when registered via addserverattr +true,0,0,q,all null exec hpup from srvsel.getserverstable[],1,1,hpup is null when registered via addserverattr +run,0,0,q,"srvsel.addserverfull[4i;`myproc;`hdb;`:localhost:5555;(enlist`date)!enlist 2024.12.01]",1,1,register server with full details via addserverfull +true,0,0,q,4=count srvsel.getserverstable[],1,1,fourth server registered via addserverfull +true,0,0,q,`myproc~first exec procname from srvsel.getserverstable[] where handle=4i,1,1,procname populated via addserverfull +true,0,0,q,`:localhost:5555~first exec hpup from srvsel.getserverstable[] where handle=4i,1,1,hpup populated via addserverfull + +/ ---- setserveractive: marking active/inactive ---- +comment,,,,,,,setserveractive - active flag management +run,0,0,q,srvsel.setserveractive[2i;0b],1,1,mark second rdb server inactive +true,0,0,q,not (exec active from srvsel.getserverstable[] where handle=2i)[0],1,1,handle 2 is now inactive +true,0,0,q,(exec active from srvsel.getserverstable[] where handle=1i)[0],1,1,handle 1 remains active +run,0,0,q,srvsel.setserveractive[2i;1b],1,1,mark second rdb server active again +true,0,0,q,(exec active from srvsel.getserverstable[] where handle=2i)[0],1,1,handle 2 is active again + + +/ ---- getservers ---- +comment,,,,,,,getservers - server lookup with attribute match scoring +true,0,0,q,`serverid`procname`servertype`hpup`handle`lastp`attributes`attribmatch~cols srvsel.getservers[`;`;()!()],1,1,getservers returns table with correct columns +true,0,0,q,count[select from srvsel.getserverstable[] where active]=count srvsel.getservers[`;`;()!()],1,1,getservers with ` lookups returns all active servers +true,0,0,q,all `hdb=exec servertype from srvsel.getservers[`servertype;`hdb;()!()],1,1,getservers filters by servertype correctly +true,0,0,q,0=count srvsel.getservers[`servertype;`nonexistent;()!()],1,1,getservers returns empty table for unknown servertype +true,0,0,q,00 but no log file - cannot replay"]; + r:$[(tabs~`) and syms~`; + runreplay[lf;sd`rowcount]; / all/all: root upd handles it + [origupd:$[`upd in key `.;`. `upd;{[t;x]}]; / narrowed: wrap root upd + @[`.;`upd;:;replayfilter[origupd;$[tabs~`;sd`tables;(),tabs];syms]]; + rr:runreplay[lf;sd`rowcount]; + @[`.;`upd;:;origupd]; / restore, success or failure + rr] + ]; + $[-7h=type r; + .z.m.log[`info][`subscriptions;"replayed ",(string sd`rowcount)," message(s) from ",string lf]; + .z.m.log[`error][`subscriptions;"replay failed for ",(string lf),": ",last r]]; + } + +/ subscribe over an already-open tickerplant handle `tph` (di.proc.rdb obtains it via +/ di.torq.servers). tabs/syms: ` for all, else a list. replay: 1b to replay the tp log. +/ Returns the subscription-details dict (tables/schemas/logfile/rowcount/date). +subscribe:{[tph;tabs;syms;replay] + sd:tph(`.u.subdetails;tabs;syms); + / define the subscribed tables at ROOT from the returned schemas (they carry g# etc.). + / @[`.;name;:;schema] targets root explicitly - a bare `name set schema` from inside + / this module would create the table in the module's private namespace instead. + {@[`.;x;:;y]}'[key sd`schemas;value sd`schemas]; + if[replay and 0&2 + echo "(run torqx.sh from your project directory, or set SETENV=/path/to/setenv.sh)" >&2 + exit 1 +fi + +: "${TORQXHOME:?TORQXHOME must be set (see setenv.sh)}" +: "${TORQXAPPCONFIG:?TORQXAPPCONFIG must be set (see setenv.sh)}" +: "${TORQXAPPHOME:?TORQXAPPHOME must be set (see setenv.sh)}" +: "${TORQXSTACKID:?TORQXSTACKID must be set (see setenv.sh)}" + +CSVPATH="$TORQXAPPCONFIG/process.csv" +LOGDIR="${TORQXLOGDIR:-/tmp}" +mkdir -p "$LOGDIR" + +if [ ! -f "$CSVPATH" ]; then + echo "ERROR: process.csv not found at $CSVPATH" >&2 + exit 1 +fi + +getfield() { + # $1 = line number in process.csv, $2 = column name + local fieldno + fieldno=$(awk -F, -v col="$2" 'NR==1{for(i=1;i<=NF;i++) if($i==col) print i}' "$CSVPATH") + awk -F, -v n="$1" -v f="$fieldno" 'NR==n{print $f}' "$CSVPATH" +} + +findprocno() { + awk -F, -v name="$1" 'NR>1 && $4==name{print NR; exit}' "$CSVPATH" +} + +allprocnames() { + awk -F, 'NR>1{print $4}' "$CSVPATH" +} + +findproc() { + # $1 = proctype, $2 = procname -> prints matching pid(s), if any. + # The token after -procname must be a SPACE or END-OF-LINE, not just a space: a + # trailing-space-only pattern silently fails to match a portless process (e.g. the + # loader, `-p` omitted), whose command line ends right at the procname with nothing + # after it - making it invisible to status/stop and letting start spawn a duplicate. + # The ( |$) still guards against a prefix collision (procname `rdb1` must not match + # `rdb10`), which a bare `-procname $2` would allow. + pgrep -f "\-torqxstackid ${TORQXSTACKID} \-proctype $1 \-procname $2( |\$)" +} + +session_name() { + # $1 = procname -> the tmux session name for this stack's process. + # Intuitively named so a developer can `tmux attach -t -` directly. + # tmux treats ':' and '.' specially in target syntax, so sanitise them out (defensive - + # stackids/procnames are alphanumeric+hyphen in practice). + printf '%s-%s' "$TORQXSTACKID" "$1" | tr ':.' '__' +} + +require_tmux() { + if ! command -v tmux >/dev/null 2>&1; then + echo "ERROR: tmux mode requested but tmux is not installed" >&2 + return 1 + fi +} + +resolverow() { + # $1 = procname -> sets PROCTYPE/PORT globals, or returns 1 if not found + local procno + procno=$(findprocno "$1") + if [ -z "$procno" ]; then + echo "ERROR: no process.csv row for procname '$1'" >&2 + return 1 + fi + PROCTYPE=$(getfield "$procno" proctype) + PORT=$(getfield "$procno" port) + return 0 +} + +start_one() { + local procname="$1"; shift + resolverow "$procname" || return 1 + local pid + pid=$(findproc "$PROCTYPE" "$procname") + if [ -n "$pid" ]; then + echo "$procname is already running (pid $pid)" + return 0 + fi + # the process is down; clear any lingering tmux session for it (e.g. a `remain-on-exit` pane left + # by an earlier tmux run that crashed or was stopped) so we never end up with an orphan session + # coexisting with a freshly-started process - in either mode. + if command -v tmux >/dev/null 2>&1 && tmux has-session -t "$(session_name "$procname")" 2>/dev/null; then + echo " (clearing lingering tmux session $(session_name "$procname"))" + tmux kill-session -t "$(session_name "$procname")" 2>/dev/null + fi + local portarg="" + if [ -n "$PORT" ] && [ "$PORT" != "0" ]; then + portarg="-p $PORT" + fi + local logfile="$LOGDIR/torqx_${TORQXSTACKID}_${procname}.log" + if [ -n "$TMUX_MODE" ]; then + start_one_tmux "$procname" "$portarg" "$logfile" "$@" + return + fi + echo "starting $procname ($PROCTYPE)... log: $logfile" + QINIT="$TORQXHOME/di/torq/bin/torqx_init.q" nohup $QCMD \ + -torqxstackid "$TORQXSTACKID" -proctype "$PROCTYPE" -procname "$procname" \ + $portarg "$@" > "$logfile" 2>&1 & + disown +} + +start_one_tmux() { + # start the process inside a detached, attachable tmux session instead of nohup+redirect, + # so a developer can attach to a live q) console. Same -torqxstackid/-proctype/-procname + # command-line signature as the nohup path, so findproc (pgrep) - and therefore stop/status - + # work identically regardless of how the process was started. $1=procname (PROCTYPE/PORT are + # already set by the caller's resolverow), $2=portarg, $3=logfile, rest=extra torqx_init.q args. + local procname="$1"; local portarg="$2"; local logfile="$3"; shift 3 + require_tmux || return 1 + local sess; sess=$(session_name "$procname") + echo "starting $procname ($PROCTYPE) in tmux session '$sess'... log: $logfile" + # Reproduce torqx.sh's exact QHOME/QLIC inside the pane so q's license resolution matches the + # nohup path. If they are set here, pass them through; if UNSET (the common "let q infer QHOME + # from the location of its own binary" setup, e.g. q at ~/.kx/bin/q with the licence at ~/.kx), + # force them unset in the pane so a stale value cannot override that inference. Two things would + # otherwise inject a stale QHOME: (a) a login shell sourcing the user's profile - which is why we + # use `bash -c`, NOT `bash -lc`; and (b) a pre-existing tmux server handing the pane its own + # environment - which the explicit -u guards below defeat regardless. + local uflags="" aflags="" + if [ -n "${QHOME+x}" ]; then aflags="$aflags QHOME=$QHOME"; else uflags="$uflags -u QHOME"; fi + if [ -n "${QLIC+x}" ]; then aflags="$aflags QLIC=$QLIC"; else uflags="$uflags -u QLIC"; fi + # re-source setenv.sh inside the pane so the TORQX*/QPATH/PATH/QCMD vars are correct even if a + # pre-existing tmux server handed us a stale environment. $extra args are embedded (the pane runs + # a single bash -c string), then env applies the QHOME/QLIC policy above before exec'ing q. + local extra="$*" + tmux new-session -d -s "$sess" -c "$PWD" \ + "bash -c 'source \"$SETENV\" && exec env $uflags QINIT=\"\$TORQXHOME/di/torq/bin/torqx_init.q\" $aflags \$QCMD -torqxstackid \"\$TORQXSTACKID\" -proctype \"$PROCTYPE\" -procname \"$procname\" $portarg $extra'" + # keep a crashed process's pane (and its stack trace) visible instead of the session vanishing + tmux set-option -t "$sess" remain-on-exit on >/dev/null + # tee the pane to the usual logfile so logs still exist in tmux mode + tmux pipe-pane -t "$sess" "cat >> \"$logfile\"" >/dev/null + echo " attach with: torqx.sh attach $procname (or: tmux attach -t $sess)" +} + +stop_one() { + local procname="$1" + resolverow "$procname" || return 1 + local unitfile="$TORQXAPPHOME/systemd/torqx-${TORQXSTACKID}-${procname}.service" + if [ -f "$unitfile" ]; then + echo "ERROR: $procname has a systemd unit ($unitfile) - stop it with" \ + "'systemctl --user stop torqx-${TORQXSTACKID}-${procname}.service', not torqx.sh" >&2 + return 1 + fi + local pid + pid=$(findproc "$PROCTYPE" "$procname") + if [ -z "$pid" ]; then + echo "$procname is not running" + return 0 + fi + echo "stopping $procname (pid $pid)..." + kill $pid + # if it was started in tmux, clean up its session too (harmless no-op otherwise). Covers both + # a live session and a lingering remain-on-exit dead pane. + if command -v tmux >/dev/null 2>&1; then + tmux kill-session -t "$(session_name "$procname")" 2>/dev/null + fi +} + +export_one() { + local procname="$1" + resolverow "$procname" || return 1 + local portarg="" + if [ -n "$PORT" ] && [ "$PORT" != "0" ]; then + portarg="-p $PORT" + fi + local unitdir="$TORQXAPPHOME/systemd" + mkdir -p "$unitdir" + local unitfile="$unitdir/torqx-${TORQXSTACKID}-${procname}.service" + cat > "$unitfile" </dev/null 2>&1; then + panepid=$(tmux list-panes -t "$(session_name "$procname")" -F '#{pane_pid}' 2>/dev/null | head -1) + fi + if [ -n "$pid" ]; then + [ -n "$panepid" ] && [ "$pid" = "$panepid" ] && tmuxtag=" (tmux)" + printf "%-15s %-10s up pid=%s%s\n" "$procname" "$PROCTYPE" "$pid" "$tmuxtag" + else + [ -n "$panepid" ] && tmuxtag=" (tmux session lingering)" + printf "%-15s %-10s down%s\n" "$procname" "$PROCTYPE" "$tmuxtag" + fi +} + +list_tmux_sessions() { + # print this stack's live tmux sessions (one per process), or a hint if there are none + local prefix="${TORQXSTACKID}-" + local found + found=$(tmux list-sessions -F '#{session_name}' 2>/dev/null | grep -F -- "$prefix" || true) + if [ -z "$found" ]; then + echo "no tmux sessions for stack '$TORQXSTACKID' (start processes with 'start --tmux' / 'devstart')" + return 0 + fi + echo "attachable tmux sessions for stack '$TORQXSTACKID':" + echo "$found" | sed 's/^/ /' +} + +attach_cmd() { + # $1 = procname (or empty/"all" -> list). Attaches to the process's tmux session; from inside + # tmux, switches the current client instead of nesting. + require_tmux || return 1 + local procname="$1" + if [ -z "$procname" ] || [ "$procname" = "all" ]; then + list_tmux_sessions + return 0 + fi + resolverow "$procname" || return 1 + local sess; sess=$(session_name "$procname") + if ! tmux has-session -t "$sess" 2>/dev/null; then + echo "ERROR: no tmux session '$sess' for '$procname'" >&2 + echo "(is it running in tmux mode? start it with 'torqx.sh start $procname --tmux' or 'devstart $procname')" >&2 + return 1 + fi + if [ -n "$TMUX" ]; then + tmux switch-client -t "$sess" + else + exec tmux attach-session -t "$sess" + fi +} + +foreachtarget() { + # $1 = fn, $2 = target ("" or "all" means every row), remaining args passed through + local fn="$1"; local target="$2"; shift 2 + if [ -z "$target" ] || [ "$target" = "all" ]; then + for p in $(allprocnames); do "$fn" "$p" "$@"; done + else + "$fn" "$target" "$@" + fi +} + +usage() { + cat >&2 <.service -f" +} + +cmd="$1"; shift + +# dev-mode command aliases: devstart/devstop/devattach == start --tmux / stop / attach. +# devstart turns on tmux mode; devstop/devattach map onto the tmux-aware stop/attach paths. +case "$cmd" in + devstart) cmd="start"; TMUX_MODE=1 ;; + devstop) cmd="stop" ;; + devattach) cmd="attach" ;; +esac + +# pre-scan the remaining args: pull out the --tmux/-t flag (which may appear anywhere) so it is +# NOT forwarded to torqx_init.q, and collect the rest as the positional target + passthrough args. +target="" +args=() +for a in "$@"; do + case "$a" in + --tmux|-t) TMUX_MODE=1 ;; + *) + if [ -z "$target" ] && [ "${a#-}" = "$a" ]; then + target="$a" # first non-flag token is the target (procname|all) + else + args+=("$a") # everything else is forwarded to torqx_init.q + fi + ;; + esac +done + +case "$cmd" in + start) foreachtarget start_one "$target" "${args[@]}" ;; + stop) foreachtarget stop_one "$target" ;; + restart) foreachtarget stop_one "$target"; sleep 1; foreachtarget start_one "$target" "${args[@]}" ;; + status) foreachtarget status_one "$target" ;; + attach) attach_cmd "$target" ;; + export-systemd) foreachtarget export_one "$target"; print_export_instructions "$target" ;; + *) usage ;; +esac diff --git a/di/torq/bin/torqx_init.q b/di/torq/bin/torqx_init.q new file mode 100644 index 00000000..b81c25ac --- /dev/null +++ b/di/torq/bin/torqx_init.q @@ -0,0 +1,26 @@ +/ TorqX generic entry point - loaded via QINIT, on demand, never copied into a +/ project. Turns this q session into a TorqX process. Replaces per-process +/ start_.q launcher files. +/ - +/ Usage (via an alias such as `alias torqx='QINIT=$TORQXHOME/di/torq/bin/torqx_init.q $QCMD'`, +/ see TorqX-POC/setenv.sh, or invoked directly by bin/torqx.sh): +/ torqx -proctype hdb -procname hdb1 (explicit identity) +/ torqx -p 5560 (auto-detect identity from process.csv) +/ torqx -p 5560 -norun (auto-detect, skip the proctype's .run hook) +/ - +/ -proctype/-procname are both-or-neither, matching di.torq's resolveidentity contract +/ - omit both to auto-detect from process.csv via this session's listening port. +/ -norun is a bare flag (no value) - single dash, matching q's own -p/-proctype/-procname +/ convention. .Q.opt gives it an empty-list value when no value follows, so its presence +/ as a key in params is enough to detect it - no need to inspect raw .z.x. + +params:.Q.opt .z.x; +proctype:$[`proctype in key params;`$first params`proctype;`]; +procname:$[`procname in key params;`$first params`procname;`]; +norun:`norun in key params; + +tq:use`di.torq; +overrides:$[norun;enlist[`norun]!enlist 1b;()!()]; +result:tq.init[proctype;procname;overrides]; + +-1 "torqx: started ",(string result`proctype)," ",string result`procname; diff --git a/di/torq/config/VERSION b/di/torq/config/VERSION new file mode 100644 index 00000000..6c6aa7cb --- /dev/null +++ b/di/torq/config/VERSION @@ -0,0 +1 @@ +0.1.0 \ No newline at end of file diff --git a/di/config/config.md b/di/torq/config/config.md similarity index 76% rename from di/config/config.md rename to di/torq/config/config.md index f6a10549..2b079ba1 100644 --- a/di/config/config.md +++ b/di/torq/config/config.md @@ -1,19 +1,19 @@ -# di.config +# di.torq.config Configuration loading and cascade resolution for the modular TorQ world. It replaces TorQ's in-process config handling (`torq.q`: `loadf`, `loadconfig`, `loadaddconfig`, -`overrideconfig`). `di.config` resolves a settings **cascade** over a builtin root and an +`overrideconfig`). `di.torq.config` resolves a settings **cascade** over a builtin root and an app root — reading **both** flat `name:value` `.q` files and `.toml` files — and returns the merged configuration as **one flat dict**. `di.torq` calls it once at startup (`config:cascade[...]`) and hands that dict to each module's `init`. ## The config model — one flat dict -`di.config` resolves config into a **returned flat dict**; it does not execute settings +`di.torq.config` resolves config into a **returned flat dict**; it does not execute settings files into namespaces or hold any global store. This is the shape `di.torq` consumes: ```q -config:use`di.config +config:use`di.torq.config cfg:config.cascade[builtinroot;approot;`rdb;`rdb1] / -> `subscribeto`rows`... !(...) / di.torq stamps identity and hands the whole dict to each module's init: cfg:cfg,`proctype`procname!(`rdb;`rdb1) @@ -46,9 +46,9 @@ builtin/default(.q,.toml) → app/default → builtin/{proctype} → app/{procty `overrideconfig` sits on **top** of all of this — the command-line layer (see below). -> **Note — name-major, not root-major.** The KDBX-POC's own vendored `di.config` used +> **Note — name-major, not root-major.** The KDBX-POC's own vendored `di.torq.config` used > *root-major* precedence (all builtin tiers, then all app tiers), where `app/default` -> would beat `builtin/{proctype}`. `di.config` deliberately keeps the **name-major** rule +> would beat `builtin/{proctype}`. `di.torq.config` deliberately keeps the **name-major** rule > TorQ has always used; `.toml` support was layered on without changing it. > **Note — avoid `-` in config file paths.** A source-level backtick symbol literal @@ -61,7 +61,7 @@ builtin/default(.q,.toml) → app/default → builtin/{proctype} → app/{procty `value`, so `` `:hdb ``, `` `trade`quote ``, `` `symbol$() `` all work. Blank lines and `/`-comment lines are skipped. These are **flat** files (one process's config), **not** the namespaced, executable settings files legacy TorQ `\l`-loaded. -- **`.toml`** — delegated to **`di.toml`**, loaded lazily (only when a `.toml` file is +- **`.toml`** — delegated to **`di.util.toml`**, loaded lazily (only when a `.toml` file is actually present). TOML has no symbol type, so every TOML string comes back as a q string, never a symbol — consumers that need a symbol normalise at the point of use (`` `$ `` is a no-op on an already-a-symbol value). @@ -71,7 +71,7 @@ builtin/default(.q,.toml) → app/default → builtin/{proctype} → app/{procty `cascade` and `parsefile` need no `init` and no logger — call them directly: ```q -config:use`di.config +config:use`di.torq.config cfg:config.cascade["/opt/torqx/di/torq/settings";"/opt/app/settings";`rdb;`rdb1] ``` @@ -80,8 +80,8 @@ fallback. Pass an already-conforming binary `` `info`warn`error `` dict of `{[c; loggers (context symbol, message string); the module performs **no** adaptation. ```q -/ option 1: di.log — the standard logger (exports binary info/warn/error) -logger:use`di.log +/ option 1: di.util.log — the standard logger (exports binary info/warn/error) +logger:use`di.util.log logdep:`info`warn`error!(logger.info;logger.warn;logger.error) config.init[enlist[`log]!enlist logdep] @@ -95,14 +95,14 @@ config.init[enlist[`log]!enlist mylog] A logger that is *not* already binary `{[c;m]}` (e.g. a raw monadic [`kx.log`](https://github.com/KxSystems/logging) instance) must be wrapped by the caller -first — di.config does no wrapping. +first — di.torq.config does no wrapping. ## Exported functions | Function | Signature | Description | |---|---|---| | `cascade` | `cascade[builtinroot;approot;proctype;procname]` | Resolve the settings cascade over the two roots × the `default`/`{proctype}`/`{procname}` name sequence and **return one flat dict**. Pure — no `init`, no logger, no globals. Precedence is name-major with `.toml > .q` within a tier (see above). A key set nowhere is simply absent; an all-missing cascade returns an empty dict. | -| `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.toml` on `QPATH` signals a clear error naming the file. Pure. | +| `parsefile` | `parsefile[path]` | Parse a single settings file into a flat dict. A `.toml` path is delegated to `di.util.toml` (loaded lazily, behind the guard rail below); a `.q` path is flat `name:value` lines. A missing file (either extension) → empty dict. An existing `.toml` file with no `di.util.toml` on `QPATH` signals a clear error naming the file. Pure. | | `overrideconfig` | `overrideconfig[config;params]` | Apply the **command-line override layer** on top of a resolved config dict — the top tier of the cascade. `di.torq` parses the process command line (`.Q.opt .z.x`) and calls this after `cascade`, so launch-time flags (e.g. `-loglevel info`, `-rows 5000`) win over the settings files. `config` is the dict from `cascade`; `params` is a dict keyed by setting name (symbol) with string (or list-of-string) values, each parsed into that setting's **existing** type. Only keys already present with a basic type are overridden; unknown keys, non-basic types, unparseable values, and multi-value overrides of a single-valued (scalar/string) setting are logged and skipped. A vector setting (e.g. a symbol list) accepts multiple values. Returns the **updated config dict**. Requires `init`. | | `init` | `init[deps]` | Wire the injected logger for `overrideconfig`. `deps` is a dict with a required `log` key — an already-conforming binary `` `info`warn`error `` dict of `{[c;m]}` functions. Errors immediately if the log dependency is missing or malformed. | | `getapimeta` | `getapimeta[]` | This module's API metadata — one `(name;public;descrip;params;return)` row per exported function, for `di.torq` to register with `di.api`. | @@ -114,55 +114,55 @@ Internal helpers — `parsetier` (per-tier `.q`+`.toml` merge), `applyoverride`, | Injectable | Required keys | Function signature | |---|---|---| -| `log` | `` `info`warn`error `` | `{[c;m]}` (context symbol, message string). Caller passes an already-conforming binary dict — built from `di.log` or hand-rolled. No adaptation is done in the module. Needed only by `overrideconfig`. | +| `log` | `` `info`warn`error `` | `{[c;m]}` (context symbol, message string). Caller passes an already-conforming binary dict — built from `di.util.log` or hand-rolled. No adaptation is done in the module. Needed only by `overrideconfig`. | ## Hard dependencies -None mandatory. `cascade`/`parsefile` gain a **lazy, soft dependency on `di.toml`**: it is +None mandatory. `cascade`/`parsefile` gain a **lazy, soft dependency on `di.util.toml`**: it is `` use``d only when a `.toml` file is actually encountered, so the `.q`-only path needs -nothing. **di.toml does not need to be in the repo (or on `QPATH`) for di.config to load or +nothing. **di.util.toml does not need to be in the repo (or on `QPATH`) for di.torq.config to load or run** — it is required only at the moment a `.toml` settings file is actually parsed. ### The `.toml` guard rail -`parsefile` guards the di.toml load so a missing module produces a clear, actionable error +`parsefile` guards the di.util.toml load so a missing module produces a clear, actionable error rather than a cryptic `notfound`. The order is deliberate: 1. **Check the file exists first.** A missing file (either extension) → empty dict. So a - missing `.toml` tier *never* triggers the di.toml requirement — the internal + missing `.toml` tier *never* triggers the di.util.toml requirement — the internal `parsetier`/`cascade` probe `base,".toml"` on every tier, and absent tiers cost nothing. -2. **Then, only for a `.toml` file that actually exists, require di.toml.** The internal - `requiretoml` helper attempts `` use`di.toml `` under protected evaluation; if it is not +2. **Then, only for a `.toml` file that actually exists, require di.util.toml.** The internal + `requiretoml` helper attempts `` use`di.util.toml `` under protected evaluation; if it is not found, it signals a clear error **naming the offending file**: ``` - 'di.config: cannot parse TOML file '/path/to/x.toml' - the di.toml module was not found - on QPATH; a di.toml module is required to parse .toml settings (underlying: notfound: di.toml) + 'di.torq.config: cannot parse TOML file '/path/to/x.toml' - the di.util.toml module was not found + on QPATH; a di.util.toml module is required to parse .toml settings (underlying: notfound: di.util.toml) ``` -3. **Parse.** With di.toml resolved, the file is delegated to it. +3. **Parse.** With di.util.toml resolved, the file is delegated to it. Because this signal happens at config-resolution time — *before* the logger dependency is wired — it surfaces via the raised error (which aborts startup with the reason), not via the injected logger. -### Contract di.config expects from di.toml +### Contract di.torq.config expects from di.util.toml -A di.toml module must export a **`parsefile`** function taking a settings-file path string +A di.util.toml module must export a **`parsefile`** function taking a settings-file path string and returning a **flat dict** of `setting → value`: ```q -(use`di.toml)[`parsefile] "/path/to/settings.toml" / -> `dir`rows!(":appdb";100) +(use`di.util.toml)[`parsefile] "/path/to/settings.toml" / -> `dir`rows!(":appdb";100) ``` -TOML has no symbol type, so di.toml returns every TOML string as a **q char string** (never -a symbol); di.config applies no coercion, so consumers that need a symbol normalise at the +TOML has no symbol type, so di.util.toml returns every TOML string as a **q char string** (never +a symbol); di.torq.config applies no coercion, so consumers that need a symbol normalise at the point of use (`` `$ `` is a no-op on an already-a-symbol value). -> **⚠️ `di.toml` is not yet in kdbx-modules** — it currently lives only in the KDBX-POC and -> lands here with the PoC merge (a di.toml module is in development against the contract +> **⚠️ `di.util.toml` is not yet in kdbx-modules** — it currently lives only in the KDBX-POC and +> lands here with the PoC merge (a di.util.toml module is in development against the contract > above). Until it is on `QPATH`, the `.toml` half of a tier is **dormant** in this repo: a > `.toml` file that exists but cannot be parsed raises the guard error above; the `.q` path -> works standalone. Full `.toml` resolution is verified in the PoC (where `di.toml` is -> vendored); this repo's suite covers the guard's error path (di.toml absent) and the +> works standalone. Full `.toml` resolution is verified in the PoC (where `di.util.toml` is +> vendored); this repo's suite covers the guard's error path (di.util.toml absent) and the > file-exists-before-delegation ordering. ## Design notes & open gaps @@ -181,7 +181,7 @@ point of use (`` `$ `` is a no-op on an already-a-symbol value). a deliberate, separately-designed addition — not a silent revival of the globals path. - **`overrideconfig` is the command-line layer, applied by `di.torq` — not a manual step.** It mirrors TorQ's `overrideconfig`/`override[]`, which TorQ runs at startup off - `.Q.opt .z.x` so launch-time flags beat the settings files. di.config just does the + `.Q.opt .z.x` so launch-time flags beat the settings files. di.torq.config just does the type-aware apply onto the resolved dict (which is why it stays env-free and never reads `.z.x` itself). It deviates from TorQ deliberately on error handling: per-setting problems (unknown name, non-basic type, value that won't parse to the target type) are logged and @@ -199,7 +199,7 @@ point of use (`` `$ `` is a no-op on an already-a-symbol value). TOML has no symbol type, so a `.toml`-origin setting like `dir = ":appdb"` or `loglevel = "info"` comes back as a string — without this, such settings could not be command-line-overridden at all, whereas their `.q`-origin symbol equivalents (`` dir:`:appdb ``) - could. di.config stays policy-free: it preserves whatever type the setting already had + could. di.torq.config stays policy-free: it preserves whatever type the setting already had (string in, string out; symbol in, symbol out), leaving symbol-vs-string normalisation to the consumer as everywhere else. - **The sentinel merge key.** `cascade`'s accumulator is seeded with a sentinel @@ -216,38 +216,38 @@ point of use (`` `$ `` is a no-op on an already-a-symbol value). ```q k4unit:use`di.k4unit -k4unit.moduletest`di.config +k4unit.moduletest`di.torq.config ``` -The `.toml` path is exercised in the KDBX-POC (where `di.toml` is vendored), not here — +The `.toml` path is exercised in the KDBX-POC (where `di.util.toml` is vendored), not here — see the hard-dependencies note above. ## Follow-ups (deferred until other modules land) -di.config is complete for v1 in isolation. The items below are intentionally deferred; +di.torq.config is complete for v1 in isolation. The items below are intentionally deferred; each is keyed to the module or milestone that unblocks it. ### ⚠️ Logging call convention — NOT set in stone (ask before changing) -di.config uses the **three-flat-var** convention (`.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`), +di.torq.config uses the **three-flat-var** convention (`.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`), matching `consistency.md` and `di.compression`, but the project hasn't finalised this versus -the **single-dict** form (`.z.m.log[\`info][…]`). **Before changing di.config's logging — or +the **single-dict** form (`.z.m.log[\`info][…]`). **Before changing di.torq.config's logging — or wiring logging in another module — stop and ask the user which convention is authoritative.** Switching is mechanical (storage + call sites only; the injected input contract is identical). -### When `di.toml` lands in kdbx-modules (with the PoC merge) +### When `di.util.toml` lands in kdbx-modules (with the PoC merge) -- **Add committed `.toml` tests.** Today `di.toml` is not on this repo's `QPATH`, so a +- **Add committed `.toml` tests.** Today `di.util.toml` is not on this repo's `QPATH`, so a committed `.toml`/mixed-tier test would fail here (verified in the PoC instead). Once - `di.toml` resolves, add tests covering: a `.toml` tier parsed into the dict, `.toml` + `di.util.toml` resolves, add tests covering: a `.toml` tier parsed into the dict, `.toml` winning over `.q` within a tier, and a mixed `.q`+`.toml` cascade. -### When `di.log` merges to main +### When `di.util.log` merges to main -- **Add a committed `di.log` integration test.** The contract match (binary +- **Add a committed `di.util.log` integration test.** The contract match (binary `` `info`warn`error `` dict) is verified manually and stood in for by the kx.log-wrapper - emission test. Once `di.log` resolves on `QPATH`, add a test that builds the dict from - `di.log` and drives `overrideconfig` through it. + emission test. Once `di.util.log` resolves on `QPATH`, add a test that builds the dict from + `di.util.log` and drives `overrideconfig` through it. ### When `di.torq` is built @@ -255,11 +255,11 @@ Switching is mechanical (storage + call sites only; the injected input contract `di.torq`/`di.inttest`, not here) exercising: `di.torq` resolves `KDBCONFIG`/`KDBAPPCONFIG` → roots and `proctype`/`procname` → identity, calls `cascade`, then `overrideconfig` with the command-line params, then hands the resolved dict to each module's `init`. -- **Hold the env-free boundary.** di.config reads no env vars or process identity — di.torq +- **Hold the env-free boundary.** di.torq.config reads no env vars or process identity — di.torq owns that resolution and passes the roots and identity explicitly. -### When `di.depcheck` is built (versioning rollout) +### When `di.torq.depcheck` is built (versioning rollout) -- **Add a `version` export and `deps.q`.** When `di.depcheck` lands, add `version:"…"` to the - export and a minimal `deps.q` (di.config has no hard deps) as part of the coordinated - repo-wide rollout, not a di.config-only change. +- **Add a `version` export and `deps.q`.** When `di.torq.depcheck` lands, add `version:"…"` to the + export and a minimal `deps.q` (di.torq.config has no hard deps) as part of the coordinated + repo-wide rollout, not a di.torq.config-only change. diff --git a/di/config/config.q b/di/torq/config/config.q similarity index 82% rename from di/config/config.q rename to di/torq/config/config.q index 8feb594b..9222f54b 100644 --- a/di/config/config.q +++ b/di/torq/config/config.q @@ -5,44 +5,44 @@ / the roots and process identity. / precedence is name-major (more specific NAME wins; within a name the app root wins) and, within a / tier, .toml wins over .q. cascade/parsefile are pure (no init/logger) - di.torq resolves config -/ before the logger exists; only overrideconfig logs, so only it needs init. di.toml is a soft dep -/ (not yet in kdbx-modules): parsefile loads it lazily, only when a .toml file is present. +/ before the logger exists; only overrideconfig logs, so only it needs init. di.util.toml is a soft dep: +/ parsefile loads it lazily, only when a .toml file is present (so a .q-only app needs no toml module). init:{[deps] / wire the injected logger (required by overrideconfig; no fallback). deps: a dict with a `log / key holding a binary `info`warn`error dict of {[c;m]} loggers. cascade/parsefile don't need init. if[99h<>type deps; - '"di.config: deps must be a dict with `log key"]; + '"di.torq.config: deps must be a dict with `log key"]; if[not `log in key deps; - '"di.config: log dependency is required; pass `info`warn`error functions keyed on `log"]; + '"di.torq.config: log dependency is required; pass `info`warn`error functions keyed on `log"]; if[99h<>type deps`log; - '"di.config: log value must be a dict; pass `info`warn`error functions"]; + '"di.torq.config: log value must be a dict; pass `info`warn`error functions"]; if[not all (`info`warn`error) in key deps`log; - '"di.config: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + '"di.torq.config: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; .z.m.loginfo:deps[`log]`info; .z.m.logwarn:deps[`log]`warn; .z.m.logerr:deps[`log]`error; - .z.m.loginfo[`init;"di.config initialised"]; + .z.m.loginfo[`init;"di.torq.config initialised"]; }; / --- settings cascade resolution (.q + .toml -> flat dict) --- requiretoml:{[path] - / internal - resolve di.toml to parse a .toml file. di.toml is a soft dep (needed only once a + / internal - resolve di.util.toml to parse a .toml file. di.util.toml is a soft dep (needed only once a / .toml file appears); guard the load so a missing one gives a clear error naming the file, not a - / cryptic `notfound: di.toml`. returns the di.toml module. - :@[use;`di.toml;{[p;e] - msg:"di.config: cannot parse TOML file '",p,"' - the di.toml module was not found on QPATH; "; - msg,:"a di.toml module is required to parse .toml settings (underlying: ",e,")"; + / cryptic `notfound: di.util.toml`. returns the di.util.toml module. + :@[use;`di.util.toml;{[p;e] + msg:"di.torq.config: cannot parse TOML file '",p,"' - the di.util.toml module was not found on QPATH; "; + msg,:"a di.util.toml module is required to parse .toml settings (underlying: ",e,")"; 'msg }[path;]]; }; parsefile:{[path] - / parse ONE settings file into a flat dict. .toml -> di.toml (via requiretoml); .q -> flat + / parse ONE settings file into a flat dict. .toml -> di.util.toml (via requiretoml); .q -> flat / `name:value` lines (split on first ":", RHS through value). blank, "/"-comment and non-pair / (no ":") lines are skipped; a missing file -> empty dict. existence is checked FIRST, so a - / missing .toml tier never triggers the di.toml requirement. + / missing .toml tier never triggers the di.util.toml requirement. fsym:`$":",path; if[0=count key fsym; :()!()]; if[path like "*.toml"; :(requiretoml[path])[`parsefile] path]; @@ -71,9 +71,9 @@ cascade:{[builtinroot;approot;proctype;procname] / "/" base and read a file named ".q"/".toml". a null means identity resolution failed, so / surface it. (a null symbol is still type -11h, so the null check is separate from the type check.) if[not all -11h=type each (proctype;procname); - '"di.config: cascade requires proctype and procname to be symbol atoms"]; + '"di.torq.config: cascade requires proctype and procname to be symbol atoms"]; if[(null proctype)|null procname; - '"di.config: cascade requires non-null proctype and procname; got ",(-3!proctype)," and ",-3!procname]; + '"di.torq.config: cascade requires non-null proctype and procname; got ",(-3!proctype)," and ",-3!procname]; dirs:(builtinroot;approot); / dedup (distinct keeps first-occurrence order, preserving least->most-specific). without it a / repeated name re-applies its tier at a LATER slot: procname~proctype is redundant, but @@ -139,17 +139,17 @@ overrideconfig:{[config;params] / setting's existing type. unknown keys, non-basic types and bad values are logged and skipped / (never aborts the batch, never writes a null). returns the updated config dict. if[99h<>type config; - .z.m.logerr[`overrideconfig;err:"di.config: config must be a dict"]; + .z.m.logerr[`overrideconfig;err:"di.torq.config: config must be a dict"]; 'err; ]; if[99h<>type params; - .z.m.logerr[`overrideconfig;err:"di.config: params must be a dict keyed by setting name"]; + .z.m.logerr[`overrideconfig;err:"di.torq.config: params must be a dict keyed by setting name"]; 'err; ]; vars:key params; if[0 merged flat dict (name-major, .toml>.q)"; "[string: builtinroot; string: approot; symbol: proctype; symbol: procname]"; "dict: merged setting -> value"); (`overrideconfig; 1b; "apply the command-line override layer onto a resolved config dict"; "[dict: resolved config; dict: setting name (symbol) -> string or list of strings]"; "dict: updated config"); - (`parsefile; 1b; "parse one .q or .toml settings file into a flat dict"; "[string: file path (.q flat name:value, or .toml via di.toml)]"; "dict: setting -> value (empty if the file is missing)"); + (`parsefile; 1b; "parse one .q or .toml settings file into a flat dict"; "[string: file path (.q flat name:value, or .toml via di.util.toml)]"; "dict: setting -> value (empty if the file is missing)"); (`getapimeta; 0b; "this module's api metadata rows"; "[]"; "table: metadata rows")); }; diff --git a/di/config/init.q b/di/torq/config/init.q similarity index 100% rename from di/config/init.q rename to di/torq/config/init.q diff --git a/di/config/test.csv b/di/torq/config/test.csv similarity index 92% rename from di/config/test.csv rename to di/torq/config/test.csv index c257e8f7..33e42a3c 100644 --- a/di/config/test.csv +++ b/di/torq/config/test.csv @@ -1,5 +1,5 @@ action,ms,bytes,lang,code,repeat,minver,comment -before,0,0,q,cfg:use`di.config,1,1,load the module +before,0,0,q,cfg:use`di.torq.config,1,1,load the module before,0,0,q,"logtab:([]lvl:`symbol$();ctx:`symbol$();msg:())",1,1,capturing log table before,0,0,q,"mocklog:`info`warn`error!({[c;m]`logtab upsert(`info;c;m)};{[c;m]`logtab upsert(`warn;c;m)};{[c;m]`logtab upsert(`error;c;m)})",1,1,define a capturing binary logger before,0,0,q,cfg.init[enlist[`log]!enlist mocklog],1,1,init with the required log dependency @@ -13,21 +13,21 @@ before,0,0,q,"basecfg:`enabled`rows`syms`tab`byte`str!(0b;100;`a`b;([]a:`long$() before,0,0,q,"system""mkdir -p /tmp/diconfigskip""",1,1,dir for the malformed-line skip test before,0,0,q,"(`:/tmp/diconfigskip/default.q) 0: (""a:1"";"""";""/ a comment"";""straynocolon"";""b:2"")",1,1,a .q file mixing valid pairs with blank/comment/no-colon lines before,0,0,q,"system""mkdir -p /tmp/diconfigtoml""",1,1,dir for the toml-guard test -before,0,0,q,"(`:/tmp/diconfigtoml/present.toml) 0: enlist ""a = 1""",1,1,a .toml file that exists but cannot be parsed without di.toml (absent in kdbx-modules) +before,0,0,q,"(`:/tmp/diconfigtoml/present.toml) 0: enlist ""a = 1""",1,1,a .toml file that config parses by delegating to the reconciled di.util.toml (present on QPATH) comment,,,,,,,init - dependency validation fail,0,0,q,cfg.init[(::)],1,1,init rejects a non-dictionary deps fail,0,0,q,cfg.init[enlist[`foo]!enlist 1],1,1,init rejects deps without a log key fail,0,0,q,cfg.init[enlist[`log]!enlist 42],1,1,init rejects a non-dict log value fail,0,0,q,cfg.init[enlist[`log]!enlist ((enlist`info)!enlist {[c;m]})],1,1,init rejects a log dict missing warn/error -comment,,,,,,,parsefile - parse one flat .q settings file into a dict (.toml delegated to di.toml) +comment,,,,,,,parsefile - parse one flat .q settings file into a dict (.toml delegated to di.util.toml) true,0,0,q,"1~cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]`diconfiga",1,1,parsefile reads a flat name:value .q file into a dict true,0,0,q,"2=count cfg.parsefile[""/tmp/diconfigbuiltin/default.q""]",1,1,parsefile returns every setting in the file true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/default.q""]",1,1,parsefile returns an empty dict for a missing .q file true,0,0,q,"(`a`b!1 2)~cfg.parsefile[""/tmp/diconfigskip/default.q""]",1,1,parsefile skips blank/comment/no-colon lines and returns only valid pairs (no-colon line must not crash the split) -comment,,,,,,,parsefile - .toml guard rail (di.toml is a soft dep; absent in kdbx-modules so the error path is exercised here) -true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/absent.toml""]",1,1,a MISSING .toml contributes nothing and does NOT require di.toml (existence checked before delegation) -fail,0,0,q,"cfg.parsefile[""/tmp/diconfigtoml/present.toml""]",1,1,an EXISTING .toml with no di.toml on QPATH signals rather than parsing -true,0,0,q,"(@[cfg.parsefile;""/tmp/diconfigtoml/present.toml"";{x}]) like ""*di.toml module was not found*""",1,1,the .toml guard error names the missing di.toml module +comment,,,,,,,parsefile - .toml integration with the reconciled di.util.toml (existence guarded first; existing .toml delegated) +true,0,0,q,"0=count cfg.parsefile[""/tmp/diconfignope/absent.toml""]",1,1,a MISSING .toml contributes nothing and does NOT require di.util.toml (existence checked before delegation) +true,0,0,q,"1j~(cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,an EXISTING .toml now parses by delegating to di.util.toml (present on QPATH) +true,0,0,q,"-7h=type (cfg.parsefile[""/tmp/diconfigtoml/present.toml""])`a",1,1,the .toml integer came back a long - di.util.toml's typed parse flows through config.parsefile comment,,,,,,,cascade - merged flat dict over two roots x default/proctype/procname (name-major; .toml>.q within a tier) true,0,0,q,"100~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfiga",1,1,within a name the later (app) root overrides the builtin root true,0,0,q,"10~(cfg.cascade[""/tmp/diconfigbuiltin"";""/tmp/diconfigapp"";`rdb;`rdbnofile])`diconfigb",1,1,name-major: builtin proctype beats app default (would be 5 under root-major) @@ -73,7 +73,7 @@ run,0,0,q,kxinst:kxlogger.createLog[],1,1,create a real kx.log instance run,0,0,q,kxh:hopen `:/tmp/diconfigkxsink.txt,1,1,open a file sink to capture output run,0,0,q,kxinst.add[kxh;`info],1,1,route info-level output to the file sink run,0,0,q,"kxbinary:`info`warn`error!({[c;m]kxinst[`info][string[c],"": "",m]};{[c;m]kxinst[`warn][string[c],"": "",m]};{[c;m]kxinst[`error][string[c],"": "",m]})",1,1,wrap the monadic logger into the binary {[c;m]} contract -run,0,0,q,cfg.init[enlist[`log]!enlist kxbinary],1,1,re-init di.config with the conforming binary logger +run,0,0,q,cfg.init[enlist[`log]!enlist kxbinary],1,1,re-init di.torq.config with the conforming binary logger run,0,0,q,"kxres:cfg.overrideconfig[enlist[`kxrows]!enlist 5;enlist[`kxrows]!enlist enlist""7""]",1,1,drive a real info-level log through the wrapped logger run,0,0,q,hclose kxh,1,1,flush and close the file sink true,0,0,q,7~kxres`kxrows,1,1,the override was applied (returned dict carries the new value) diff --git a/di/torq/depcheck/VERSION b/di/torq/depcheck/VERSION new file mode 100644 index 00000000..6c6aa7cb --- /dev/null +++ b/di/torq/depcheck/VERSION @@ -0,0 +1 @@ +0.1.0 \ No newline at end of file diff --git a/di/depcheck/depcheck.md b/di/torq/depcheck/depcheck.md similarity index 63% rename from di/depcheck/depcheck.md rename to di/torq/depcheck/depcheck.md index 44c46011..f0b591f3 100644 --- a/di/depcheck/depcheck.md +++ b/di/torq/depcheck/depcheck.md @@ -1,4 +1,4 @@ -# di.depcheck +# di.torq.depcheck Dependency, version, core-contract, and `.z.ts`-ownership auditing for kdb-x modules. Runs once at process startup — after every module has been loaded — and reports any declared dependency that is missing, out of date, or fails the shared core-dependency contracts. It is the modernised successor to legacy TorQ's `checkdependency`/`runchk`/`checkvers`: a per-module manifest replaces the old CSV registry, and real numeric semver replaces the 5-component digit-walk. @@ -8,9 +8,9 @@ Dependency, version, core-contract, and `.z.ts`-ownership auditing for kdb-x mod - **A post-load audit, not a pre-load gate** — it runs after the host process (`di.torq`) has already `use`d every module it needs, and never calls `use` on anything it checks. Each module's state is read by introspecting the session namespace the kdb-x loader populates: every loaded module lands under `` `.m.di `` keyed by a short form (`di.timer` → `` `.m.di.0timer ``), and that module's `export` dict is readable there directly. "Not found" in a report means a *declared* dependency was never loaded — it is not a filesystem scan. - **Presence & minimum version** — for each loaded module that ships a manifest (symbol-keyed by dependency name, string-valued by minimum version), every declared dependency is checked: is it loaded, and does its exported `version` satisfy the declared minimum (real numeric `major.minor.patch` comparison)? A module with no manifest is skipped, not failed. -- **Dual-format manifests (`deps.q` and/or `deps.toml`)** — a module's dependencies are read from **both** a `deps.q` (a q dict literal) and a `deps.toml` (a `[dependencies]` section), wherever each exists, merged with **`.toml` winning on a clash** — mirroring di.config's `parsetier` so both formats can coexist mid-migration. `di.toml` is loaded **lazily and only when a `deps.toml` actually exists**; a module with only `deps.q` never triggers it. +- **Dual-format manifests (`deps.q` and/or `deps.toml`)** — a module's dependencies are read from **both** a `deps.q` (a q dict literal) and a `deps.toml` (a `[dependencies]` section), wherever each exists, merged with **`.toml` winning on a clash** — mirroring di.torq.config's `parsetier` so both formats can coexist mid-migration. `di.util.toml` is loaded **lazily and only when a `deps.toml` actually exists**; a module with only `deps.q` never triggers it. - **Transitive manifest-graph walk** — beyond each loaded module's direct deps, `checkgraph` walks the graph **on disk** (reading each peer's own manifest whether or not it is loaded), cycle-guarded via a visited set, and reports a **presence** failure for any dependency reached at depth ≥ 2 that resolves nowhere on QPATH. It loads no module code. Transitive *version* checking is deferred (see Notes); direct (depth-1) deps keep the stronger presence=*loaded*/version=*exported* check and are excluded from the walk so the two never double-report. -- **Core dependency contracts** — for whichever of `di.log`, `di.timer`, or `di.handlers` are loaded, the export dict is checked for the required keys of the contract it provides (Logging: `info`/`warn`/`error`; Timer: `addjob`/`deletejobs`/`enablejobs`/`disablejobs`/`getactivejobs`/`cp`; Handlers: `register`/`remove`/`list`). The single-contract check is also exported directly as `checkcontract[provider;requiredkeys]` for a contract this module doesn't know by name. +- **Core dependency contracts** — for whichever of `di.util.log`, `di.timer`, or `di.torq.handlers` are loaded, the export dict is checked for the required keys of the contract it provides (Logging: `info`/`warn`/`error`; Timer: `addjob`/`deletejobs`/`enablejobs`/`disablejobs`/`getactivejobs`/`cp`; Handlers: `register`/`remove`/`list`). The single-contract check is also exported directly as `checkcontract[provider;requiredkeys]` for a contract this module doesn't know by name. - **`.z.ts` ownership** — warns if `.z.ts` is bound while di.timer is absent or uninitialised (its `enabled` flag is the proxy for "di.timer's `init` ran and bound `.z.ts`"). Warning-level only, and cannot detect a later rebind — an accepted limitation. - **kdb-x engine version** (optional) — compares the running engine's `.z.K` against an optional `` `minkdbxversion `` passed alongside `log` on the same `deps` dict. Warning-level; no caller supplies a minimum today, so it is a no-op in every real invocation. @@ -38,9 +38,9 @@ A loaded dependency that exports no `version` gets its own line — `di.timer re **No hard dependencies** on other `di.*` modules — the module works standalone, and ships its own (empty) `deps.q`, dogfooding the convention it introduces. -**`di.toml` is a soft, lazy dependency** — it is not declared in `deps.q` and not loaded at import time. It is resolved once (cached) and called **only** when a module being audited ships a `deps.toml` file. A process whose modules use only `deps.q` never loads it, so it is not required to be on QPATH in that case. If a `deps.toml` *does* exist and `di.toml` is missing or fails to parse it, that is reported as one aggregated failure line (see Notes) rather than throwing. +**`di.util.toml` is a soft, lazy dependency** — it is not declared in `deps.q` and not loaded at import time. It is resolved once (cached) and called **only** when a module being audited ships a `deps.toml` file. A process whose modules use only `deps.q` never loads it, so it is not required to be on QPATH in that case. If a `deps.toml` *does* exist and `di.util.toml` is missing or fails to parse it, that is reported as one aggregated failure line (see Notes) rather than throwing. -The `log` dependency must be passed to `init` inside the `deps` dict keyed on `` `log ``, and must already match the binary `{[c;m]}` contract — the module validates key presence but does not detect or adapt other shapes (e.g. a monadic `kx.log` instance). To use `di.log`, pass its `logdict`. +The `log` dependency must be passed to `init` inside the `deps` dict keyed on `` `log ``, and must already match the binary `{[c;m]}` contract — the module validates key presence but does not detect or adapt other shapes (e.g. a monadic `kx.log` instance). To use `di.util.log`, pass its `logdict`. --- @@ -86,17 +86,17 @@ depcheck.checkcontract[`di.timer;`cp] / bare atom works the sa ## Usage Example ```q -/ log dep must already match the binary {[c;m]} contract - write your own, or use di.log: -/ logging:use`di.log +/ log dep must already match the binary {[c;m]} contract - write your own, or use di.util.log: +/ logging:use`di.util.log / depcheck.init[enlist[`log]!enlist logging.logdict] logdep:`info`warn`error!({[c;m]};{[c;m]};{[c;m]}) / di.torq loads every module the process needs first... timer:use`di.timer -handlers:use`di.handlers +handlers:use`di.torq.handlers / ...then depcheck audits the fully-loaded session, last -depcheck:use`di.depcheck +depcheck:use`di.torq.depcheck depcheck.init[enlist[`log]!enlist logdep] ``` @@ -106,15 +106,15 @@ depcheck.init[enlist[`log]!enlist logdep] ```q k4unit:use`di.k4unit -k4unit.moduletest`di.depcheck +k4unit.moduletest`di.torq.depcheck ``` -Run in a fresh q session — `moduletest` doesn't reset its internal result table between calls, so a second call duplicates this file's rows. The unit suite drives real, already-shipped modules rather than synthetic fixtures: **di.timer** (merged to `main`) is always loaded and exercises real gaps (no `version`; `cp` defined but unexported), while **di.kafka**, **di.handlers** (the positive control — the one module that does export `version`), **di.log**, and **di.toml** (on its own `feature-toml` branch) are all on unmerged PRs, so every assertion depending on them gracefully no-ops when the module isn't resolvable on QPATH — the suite passes standalone on a bare `feature-depcheck` checkout, exercising the real path only when the module happens to be present. The manifest readers, dual-format merge, and transitive walk are exercised against scratch modules written under a QPATH root at runtime — the q-only / toml-only / both-formats-clashing / neither cases, a deliberately-broken `deps.toml`, and an A→B→C chain with a B→A cycle — all cleaned up afterwards, with no hardcoded paths and no committed fixtures. The di.toml-dependent assertions among these no-op when di.toml is absent. +Run in a fresh q session — `moduletest` doesn't reset its internal result table between calls, so a second call duplicates this file's rows. The unit suite drives real, already-shipped modules rather than synthetic fixtures: **di.timer** (merged to `main`) is always loaded and exercises real gaps (no `version`; `cp` defined but unexported), while **di.kafka**, **di.torq.handlers** (the positive control — the one module that does export `version`), **di.util.log**, and **di.util.toml** (on its own `feature-toml` branch) are all on unmerged PRs, so every assertion depending on them gracefully no-ops when the module isn't resolvable on QPATH — the suite passes standalone on a bare `feature-depcheck` checkout, exercising the real path only when the module happens to be present. The manifest readers, dual-format merge, and transitive walk are exercised against scratch modules written under a QPATH root at runtime — the q-only / toml-only / both-formats-clashing / neither cases, a deliberately-broken `deps.toml`, and an A→B→C chain with a B→A cycle — all cleaned up afterwards, with no hardcoded paths and no committed fixtures. The di.util.toml-dependent assertions among these no-op when di.util.toml is absent. The **integration suite** (`test_integration.csv`) spins up a real, separate child kdb-x process (the child must itself be kdb-x-capable to `use` the modules) to prove two things the unit suite structurally cannot: that a genuine zero-failure run completes cleanly end to end, and that a real signalled failure terminates a real host process with a non-zero exit code and the real report in captured output. `moduletest` only ever loads `test.csv`, so load and run this suite directly: ```q k4unit:use`di.k4unit -.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.depcheck;`test_integration.csv] +.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.torq.depcheck;`test_integration.csv] .m.di.0k4unit.KUrt[] k4unit.getresults[] / one row per assertion; ok=1 is a pass ``` @@ -123,10 +123,11 @@ k4unit.getresults[] / one row per assertion; ok=1 is a pass ## Notes -- **`di.toml` coupling.** `deps.toml` is inert data parsed by the `di.toml` module (no evaluation), whereas `deps.q` is a q dict literal read by executing it. Module keys in a `[dependencies]` section must be **quoted** — `"di.timer" = "0.2.0"` — because di.toml rejects unquoted dotted keys. di.depcheck reads only string version values via `parsefile`, so it is unaffected by di.toml's scalar value-typing. All format-specific reading lives behind `finddepsq`/`readdepsq`/`finddepstoml`/`readdepstoml`/`readdeps`; every other function consumes only their merged, format-agnostic dict, so dropping a format later is a change to those readers alone. Which format the repo ultimately standardises on is an open cross-team decision (with the TorqX POC), deliberately not resolved here. -- **Deliberate divergence from di.config.** di.config's `requiretoml` throws and aborts its entire settings cascade the instant a `.toml` tier can't be read, because it must hand back one complete, correct config. di.depcheck does the **opposite** on the same event — it catches, folds one clearly-worded line (matching `requiretoml`'s wording) into the aggregate report, and keeps walking — because its whole purpose is to surface *every* problem across *many* modules in one pass. Two right answers to two different jobs, not an inconsistency. +- **`di.util.toml` coupling.** `deps.toml` is inert data parsed by the `di.util.toml` module (no evaluation), whereas `deps.q` is a q dict literal read by executing it. Module keys in a `[dependencies]` section must be **quoted** — `"di.timer" = "0.2.0"` — because di.util.toml rejects unquoted dotted keys. di.torq.depcheck reads only string version values via `parsefile`, so it is unaffected by di.util.toml's scalar value-typing. All format-specific reading lives behind `finddepsq`/`readdepsq`/`finddepstoml`/`readdepstoml`/`readdeps`; every other function consumes only their merged, format-agnostic dict, so dropping a format later is a change to those readers alone. Which format the repo ultimately standardises on is an open cross-team decision (with the TorqX POC), deliberately not resolved here. +- **Deliberate divergence from di.torq.config.** di.torq.config's `requiretoml` throws and aborts its entire settings cascade the instant a `.toml` tier can't be read, because it must hand back one complete, correct config. di.torq.depcheck does the **opposite** on the same event — it catches, folds one clearly-worded line (matching `requiretoml`'s wording) into the aggregate report, and keeps walking — because its whole purpose is to surface *every* problem across *many* modules in one pass. Two right answers to two different jobs, not an inconsistency. - **Transitive presence is walked; transitive version is not, yet.** `checkgraph` reports a missing transitive dependency at depth ≥ 2, but cannot check the *version* of an unloaded module without either loading it (which the walk must not do) or a per-module `VERSION` file. `VERSION` files are not yet a repo-wide convention — modules carry an inline exported `version` — so adopting them is a coordinated rollout; the walk gains transitive version checking for free once they land. +- **A version may be published in either place; both audits accept both.** The pre-load `checkversiongraph` reads a module's on-disk `VERSION` file (it must not load code); the post-load audit reads the loaded module's `version` **export**. These are the same source of truth published two ways, so `checkdepversion` falls back to the `VERSION` file when a loaded module withholds `version` from its export dict. Several modules legitimately do — `di.torq.servers`, `di.torq.config`, `di.util.toml` and di.torq.depcheck itself keep it out of `export` because their `getapimeta` contract test asserts the exact export set. Without the fallback, every process whose manifest declares such a module fails this audit *after* a completely successful init: `di.proc.rdb`, `di.proc.wdb` and `di.proc.gateway` all declare `di.torq.servers`, and all three died exactly there — a failure mode only a real stack boot surfaced, since those modules' unit suites do not boot a process. A module carrying neither an export nor a file is still reported as before. - **`.z.ts` ownership is a best-effort proxy.** di.timer's `enabled` flag evidences that its `init` bound `.z.ts`; it cannot detect something rebinding `.z.ts` afterwards. Scope is deliberately limited to `.z.ts` only. - **The kdb-x-version check is shape-only for now.** The comparison is implemented and unit-tested in isolation, but no caller supplies `` `minkdbxversion `` yet, so it is a no-op in every real invocation until di.torq (or another caller) threads a real minimum through. It is warning-only, not fail-fast. Uses `.z.K`, not `.z.v`, matching di.k4unit's existing precedent. - **Semver is numeric `X.Y.Z` only** — no pre-release/build-metadata support, matching every version string in this codebase. A malformed declared minimum or exported found-version is reported as its own distinct failure line rather than silently mis-compared. During 0.x.y development a passing `>=` check does not guarantee contract compatibility. -- **Modules currently missing a `version` export** — di.timer, di.kafka, and di.log were all found without one; di.handlers is the only module that exports it (and its own comments call that a placeholder pending this module). Adding `version` everywhere is a coordinated repo-wide rollout, of which di.depcheck is the consumer side. di.compression separately imports `kx.log` directly rather than following the binary `{[c;m]}` convention — a pre-`consistency.md` outlier worth its own cleanup. +- **Modules currently missing a `version` export** — di.timer, di.kafka, and di.util.log were all found without one; di.torq.handlers is the only module that exports it (and its own comments call that a placeholder pending this module). Adding `version` everywhere is a coordinated repo-wide rollout, of which di.torq.depcheck is the consumer side. di.compression separately imports `kx.log` directly rather than following the binary `{[c;m]}` convention — a pre-`consistency.md` outlier worth its own cleanup. diff --git a/di/depcheck/depcheck.q b/di/torq/depcheck/depcheck.q similarity index 61% rename from di/depcheck/depcheck.q rename to di/torq/depcheck/depcheck.q index e0ed83bd..0c31bf0b 100644 --- a/di/depcheck/depcheck.q +++ b/di/torq/depcheck/depcheck.q @@ -3,46 +3,72 @@ / introspecting the session namespace the kdb-x `use` loader already populates (`.m.di.0`), so it stays / standalone with no hard di.* dependency of its own -/ the fixed set of core dependency contracts di.depcheck knows how to validate, keyed by the module that provides -/ each one - not a generic self-declaration registry, since no such mechanism exists anywhere in this codebase yet -contracts:`di.log`di.timer`di.handlers!( +/ module version - di.torq.depcheck is the first module to carry one, dogfooding the convention it introduces + +/ the fixed set of core dependency contracts di.torq.depcheck knows how to validate, keyed by the module that provides +/ each one - not a generic self-declaration registry, since no such mechanism exists anywhere in this codebase yet. +/ NOTE (TorqX consolidation): the providers now carry their reconciled hierarchical names (di.util.log, +/ di.torq.handlers) - the session-namespace helpers below map an arbitrarily-nested name to its namespace. +contracts:`di.util.log`di.timer`di.torq.handlers!( `info`warn`error; - `addjob`deletejobs`enablejobs`disablejobs`getactivejobs`cp; + `addjob`deletejobs`enablejobs`disablejobs`getactivejobs; `register`remove`list ); +/ NOTE (TorqX consolidation): the timer contract was aligned to what di.torq actually consumes (di.torq's own +/ buildtimerdep uses these five, not `cp`). The real di.timer exports `setcp`, not a bare `cp`, so a `cp` here would +/ make checkcontracts[] fail on every startup. `checkcontract` remains generic - a caller can still audit `cp` explicitly. / ============================================================ / session-namespace introspection helpers / ============================================================ +/ The kdb-x `use` loader keys a module `vendor.a.b` under a NESTED namespace: `di.timer` -> `.m.di.0timer`, +/ `di.torq.handlers` -> `.m.di.0torq.0handlers`, `di.util.log` -> `.m.di.0util.0log`. So every segment after the +/ vendor gets a `0` prefix and the segments nest. (Generalised from the original flat single-dot assumption during +/ the TorqX consolidation, which introduced the di.torq.*/di.util.*/di.proc.* hierarchy.) shortmod:{[modname] - / di.timer -> `0timer ; kx.log -> `0log - the short form the kdb-x `use` loader keys a module under, off its - / vendor's `.m. namespace. Assumes exactly one dot (vendor.name), matching every module name seen in - / this codebase so far + / di.torq.handlers -> `0handlers - the leaf short name, the key a module sits under within its PARENT namespace `$"0",last "." vs string modname }; -shorttofull:{[s] - / `0timer -> `di.timer - only ever applied to keys of `.m.di (checkdeps walks di.* modules specifically, see - / checkdeps), so the di. prefix is correct here and does not need vendor-generalising like shortmod/modvendorns - `$"di.",1_string s +modparentns:{[modname] + / the PARENT session namespace a module is keyed under: di.timer -> `.m.di ; di.torq.handlers -> `.m.di.0torq ; + / kx.log -> `.m.kx. Every segment except the vendor and the leaf becomes a `0`-prefixed namespace segment. + p:"." vs string modname; + `$".m.",(first p),(raze ".0",/:1_-1_p) + }; + +modns:{[modname] + / a module's OWN full session namespace: di.timer -> `.m.di.0timer ; di.torq.handlers -> `.m.di.0torq.0handlers + ` sv modparentns[modname],shortmod modname }; -modvendorns:{[modname] - / di.timer -> `.m.di ; kx.log -> `.m.kx - the top-level session namespace a module's vendor is keyed under. - / a di.* module's deps.q may legitimately declare a hard dependency on an external vendor module (e.g. - / kx.log), so dependency resolution (getexport/checkonedep/checkcontract) must not hardcode `.m.di - only - / checkdeps's walk of which modules to audit as consumers is intentionally di.*-scoped - `$".m.",first "." vs string modname +nspathtomod:{[nspath] + / inverse of modns: `.m.di.0torq.0handlers -> `di.torq.handlers (drop the `.m` prefix, strip the `0` off every + / segment after the vendor) + s:2_"." vs string nspath; + `$"." sv (enlist first s),{$["0"=first x;1_x;x]} each 1_s }; getexport:{[modname] / read another already-loaded module's export dict purely via session-namespace introspection - no `use`, no import / returns (::) if the module isn't loaded, or if its export somehow can't be read sn:shortmod modname; - vns:modvendorns modname; - if[not sn in key vns;:(::)]; - @[get;`$(string vns),".",(string sn),".export";{(::)}] + pns:modparentns modname; + if[not sn in key pns;:(::)]; + @[get;` sv (modns modname),`export;{(::)}] + }; + +loadedmodules:{[] + / every loaded di.* module's FULL dotted name, walking the nested `.m.di` tree. A namespace is a loaded module iff + / it has an `export` key; it may ALSO contain child module namespaces (di.torq is both), so we emit-and-descend. + walk:{[walk;acc;nsp] + ks:@[key;nsp;{`$()}]; + acc:$[`export in ks; acc,nspathtomod nsp; acc]; + childns:ks where ks like "0*"; + walk[walk;;]/[acc; ` sv' nsp,'childns] + }; + walk[walk;();`.m.di] }; / ============================================================ @@ -70,7 +96,7 @@ readdepsq:{[modname] }; / ============================================================ -/ deps.toml loading (lazy, file-existence-gated di.toml) +/ deps.toml loading (lazy, file-existence-gated di.util.toml) / ============================================================ finddepstoml:{[modname] @@ -83,22 +109,22 @@ finddepstoml:{[modname] }; resolvetoml:{[] - / lazily resolve di.toml once and cache it in module state, returning its export dict. throws if di.toml is not + / lazily resolve di.util.toml once and cache it in module state, returning its export dict. throws if di.util.toml is not / resolvable on QPATH - caught by readdepstoml and turned into one aggregated failure line, never an abort. only ever - / called when a real deps.toml file has already been found, so a module with no deps.toml never triggers a di.toml load + / called when a real deps.toml file has already been found, so a module with no deps.toml never triggers a di.util.toml load cached:@[get;`.z.m.tomlmod;{(::)}]; if[not cached~(::);:cached]; - m:use`di.toml; + m:use`di.util.toml; .z.m.tomlmod:m; m }; readdepstoml:{[modname] - / read /deps.toml if it exists, returning (failures;depsdict). di.toml is touched ONLY when the file exists - / (file-existence-gated, exactly like di.config's parsefile checks existence before dispatching on extension). a missing - / or broken di.toml degrades to one aggregated failure line worded like di.config's requiretoml (name the file/module, - / name the underlying cause, one sentence) - but deliberately does NOT throw: di.config's requiretoml aborts its whole - / cascade because it must return one complete config, whereas di.depcheck must surface every module's problems in one + / read /deps.toml if it exists, returning (failures;depsdict). di.util.toml is touched ONLY when the file exists + / (file-existence-gated, exactly like di.torq.config's parsefile checks existence before dispatching on extension). a missing + / or broken di.util.toml degrades to one aggregated failure line worded like di.torq.config's requiretoml (name the file/module, + / name the underlying cause, one sentence) - but deliberately does NOT throw: di.torq.config's requiretoml aborts its whole + / cascade because it must return one complete config, whereas di.torq.depcheck must surface every module's problems in one / pass, so it catches, records a line, and keeps walking (see depcheck.md) p:finddepstoml modname; if[p~(::);:(();()!())]; @@ -110,18 +136,18 @@ readdepstoml:{[modname] / non-dict here would otherwise throw out of readdeps's merge and abort the whole walk) $[not `dependencies in key d;(();()!()); 99h=type d`dependencies;(();d`dependencies); - (enlist "di.depcheck: deps.toml for ",(string mn), + (enlist "di.torq.depcheck: deps.toml for ",(string mn), " has a malformed [dependencies] section - expected a table of module = \"version\" entries";()!())] }[modname;]; path; - {[mn;e] (enlist "di.depcheck: cannot read deps.toml for ",(string mn), - " - the di.toml module was not found on QPATH or failed to parse it; di.toml is required to read .toml manifests (underlying: ",e,")"; + {[mn;e] (enlist "di.torq.depcheck: cannot read deps.toml for ",(string mn), + " - the di.util.toml module was not found on QPATH or failed to parse it; di.util.toml is required to read .toml manifests (underlying: ",e,")"; ()!())}[modname;]] }; readdeps:{[modname] / merged manifest reader: reads deps.q and deps.toml where each exists and merges them, with deps.toml winning on a key - / clash - mirroring di.config's live parsetier ((parsefile base,".q"),parsefile base,".toml"). returns (failures;dict): + / clash - mirroring di.torq.config's live parsetier ((parsefile base,".q"),parsefile base,".toml"). returns (failures;dict): / failures aggregates a malformed-deps.q line and/or an unreadable-deps.toml line; dict is the merged symbol->minversion / mapping (empty if neither format is present). all format-specific reading lives here and in finddepsq/finddepstoml - / every downstream function (checkonedep/checkmoduledeps/checkdeps/checkgraph) consumes only this already-merged dict @@ -195,9 +221,20 @@ checkdepversion:{[dep;minver] / xp is (::) and throw 'type. Caught by direct testing, not by reading the code - see depcheck.md xp:getexport dep; noversionmsg:enlist string[dep]," requires minimum version ",minver,", but ",string[dep]," exports no version"; - if[xp~(::);:noversionmsg]; - if[not `version in key xp;:noversionmsg]; - checkfoundversion[dep;minver;xp`version] + ver:$[xp~(::);"";$[`version in key xp;xp`version;""]]; + / FALL BACK to the on-disk VERSION file when a loaded module withholds `version` from its export dict. Several + / modules legitimately do: di.torq.servers/di.torq.config/di.util.toml/di.torq.depcheck all ship a VERSION file + / but keep it out of `export` because their getapimeta contract test asserts the exact export set. The file is + / the same source of truth the pre-load checkversiongraph reads, so a peer that is present and correctly + / versioned must not fail this audit just because of where its version is published. Without this, every + / process whose manifest declares such a module (di.proc.{rdb,wdb,gateway} all declare di.torq.servers) dies + / here AFTER a fully successful init - see depcheck.md + if[0=count ver; + dir:resolvemodule dep; + if[not dir~(::);ver:readversion dir]]; + / neither source carries a version - the original message still reads correctly (di.timer/di.tz ship neither) + if[0=count ver;:noversionmsg]; + checkfoundversion[dep;minver;ver] }; checkonedep:{[dep;minver] @@ -206,24 +243,24 @@ checkonedep:{[dep;minver] / not vendor-restricted to di.* - a deps.q may name an external vendor module (e.g. kx.log) as a hard / dependency, so presence is checked against dep's own vendor namespace, not hardcoded to `.m.di / a manifest version must be a string (quoted in deps.toml, a q string in deps.q). a non-string value - an unquoted - / deps.toml version parsed as a float/int by di.toml, or a symbol/number in deps.q - is an authoring error reported + / deps.toml version parsed as a float/int by di.util.toml, or a symbol/number in deps.q - is an authoring error reported / as its own clear line, rather than left to corrupt the concatenated message or throw out of parsesemver's `vs`. / 10h=abs type accepts a char vector or a lone char atom (both string-ish), rejecting int/float/symbol if[not 10h=abs type minver; :enlist string[dep]," has a non-string minimum version in its manifest (got type ",(string type minver),") - versions must be quoted strings"]; depshort:shortmod dep; - vns:modvendorns dep; + vns:modparentns dep; $[not depshort in key vns; enlist string[dep]," requires minimum version ",minver,", not found"; checkdepversion[dep;minver]] }; -checkmoduledeps:{[modshort] - / checks one already-loaded module's declared deps (deps.q and/or deps.toml) against the current session. returns - / aggregated failure lines: manifest read-failures (a malformed deps.q or an unreadable deps.toml, both pre-collected - / by readdeps rather than thrown) plus each declared dependency's presence/version line. one bad manifest never aborts - / the checkdeps[] walk and masks other modules' real failures - readdeps catches, checkonedep is a pure per-pair function - modname:shorttofull modshort; +checkmoduledeps:{[modname] + / checks one already-loaded module's declared deps (deps.q and/or deps.toml) against the current session. takes a + / FULL dotted module name (generalised from a flat short name during the TorqX consolidation - a nested name like + / di.torq.handlers cannot be reconstructed from a bare `0handlers` short key). returns aggregated failure lines: + / manifest read-failures (both pre-collected by readdeps, never thrown) plus each declared dependency's presence/ + / version line. one bad manifest never aborts the checkdeps[] walk - readdeps catches, checkonedep is pure per-pair r:readdeps modname; merged:r 1; (r 0),$[0=count merged;();raze checkonedep'[key merged;value merged]] @@ -236,9 +273,9 @@ checkdeps:{[] / if two different loaded modules declare the same dependency at different minimums, each is checked / independently and both lines are emitted if both fail - checkonedep is a pure function of (dep;minver) with / no shared state across calls, so this needs no special handling. Manually verified with two real deps.q - / fixtures on disk (di.handlers required at both a satisfied and an unsatisfied minimum simultaneously) since + / fixtures on disk (di.torq.handlers required at both a satisfied and an unsatisfied minimum simultaneously) since / no real module ships a non-empty deps.q yet to build a committed, portable test against - see depcheck.md - raze checkmoduledeps each key `.m.di + raze checkmoduledeps each loadedmodules[] }; / ============================================================ @@ -248,7 +285,7 @@ checkdeps:{[] resolvemodule:{[modname] / reimplements the kdb-x `use` loader's QPATH search (colon-separated roots, first match wins; a dotted module name's / dots become path segments) to test whether a module is INSTALLED on QPATH without loading it - returns the resolved - / module directory (hsym) or (::) if nothing matches. adapted from TorqX di.depcheck's resolvemodule; deliberately does + / module directory (hsym) or (::) if nothing matches. adapted from TorqX di.torq.depcheck's resolvemodule; deliberately does / not reach into kdb-x's undocumented .Q.m.* internals. used only for transitive presence, distinct from checkonedep's / loaded-check: a module can be installed-on-QPATH yet not loaded-into-the-session relpath:ssr[string modname;".";"/"]; @@ -285,15 +322,91 @@ checkgraph:{[] / presence failure for any dependency reached at depth >= 2 that does not resolve on QPATH. depth-1 (deps directly / declared by a loaded module) stays with checkdeps (presence=loaded, version=exported); checkgraph excludes those via / the directdeps set so the two never double-report. satisfies consistency.md's on-disk / loads-no-module-code walk - / without a pre-load pass. LIMITATION: transitive VERSION checking of an unloaded module is not done here - a found - / version needs loading (forbidden) or a per-module VERSION file (deferred until a repo-wide rollout) - see depcheck.md - roots:shorttofull each key `.m.di; + / without a pre-load pass. This post-load walk does PRESENCE only; transitive VERSION checking of unloaded modules is + / handled by the pre-load checkversiongraph[] below (grafted from TorqX during the consolidation), which reads each + / module's on-disk VERSION file - lifting the limitation this function's comment used to flag - see depcheck.md. + roots:loadedmodules[]; directdeps:distinct raze {[r] key (readdeps r) 1} each roots; acc:`visited`fails!(`symbol$();()); acc:{[covered;directdeps;acc;root] visit[covered;directdeps;acc;root]}[roots;directdeps]/[acc;roots]; acc`fails }; +/ ============================================================ +/ pre-load transitive VERSION graph (on-disk, loads no module code) +/ ============================================================ +/ Grafted from TorqX di.torq.depcheck during the consolidation. Where checkdeps/checkgraph audit the LOADED session +/ (post-load introspection), these run at the very START of di.torq.init - BEFORE any module is `use`d - resolving +/ each declared dependency on QPATH and reading its VERSION file, so a peer-version mismatch is caught up front (the +/ "customer bumped di.proc.gateway but not the di.serverselect it now needs" scenario) rather than mid-startup. +/ Pure on-disk reads (resolvemodule + VERSION file + di.util.toml manifest parse) - no `use` of the checked modules. + +readversion:{[dir] + / read a resolved module directory's VERSION file WITHOUT loading the module. Returns the version string, or "" if + / the module resolved on QPATH but ships no VERSION file (present-but-unversioned - itself reportable). + vfile:hsym `$(string dir),"/VERSION"; + if[0=count key vfile;:""]; + first read0 vfile + }; + +checkinstalledversion:{[requiringmod;dep;minver] + / PRE-LOAD single-dep check: is `dep` INSTALLED on QPATH and does its on-disk VERSION meet `minver`? Uses the same + / semver (vergte/ismalformed) and non-string-minver guard as the post-load path. `requiringmod` attributes a + / transitive failure (` for the entry/app-level manifest). Returns () or an enlisted failure line. + ctx:$[null requiringmod;"";"(required by ",string[requiringmod],") "]; + if[not 10h=abs type minver; + :enlist ctx,string[dep]," has a non-string minimum version in its manifest (got type ",(string type minver),")"]; + dir:resolvemodule dep; + if[dir~(::);:enlist ctx,string[dep]," requires minimum version ",minver,", not found on QPATH"]; + have:readversion dir; + if[0=count have;:enlist ctx,string[dep]," has no VERSION file at ",string dir]; + if[ismalformed minver;:enlist ctx,string[dep]," has an invalid minimum version ",minver]; + if[ismalformed have;:enlist ctx,string[dep]," has an invalid VERSION file (",have,") at ",string dir]; + $[vergte[have;minver];();enlist ctx,string[dep]," requires minimum version ",minver,", found ",have] + }; + +visitversion:{[acc;modname] + / one node of the pre-load version graph: read modname's merged on-disk manifest (readdeps: deps.q + deps.toml), + / version-check each declared peer against its installed VERSION file, recurse. Cycle-guarded via acc`visited. + if[modname in acc`visited;:acc]; + acc[`visited]:acc[`visited],modname; + r:readdeps modname; + acc[`fails]:acc[`fails],r 0; + merged:r 1; + acc[`fails]:acc[`fails],raze checkinstalledversion[modname;;]'[key merged;value merged]; + {[acc;dep] visitversion[acc;dep]}/[acc;key merged] + }; + +raisefails:{[fails] + if[count fails;'"DEPENDENCY CHECK FAILED (peer version requirements):\n","\n" sv " ",/:fails]; + ()!() + }; + +checkversiongraph:{[entries] + / PRE-LOAD version graph from a set of entry module names (e.g. a built-in proctype's di.proc.* entry module). + / Walks each entry's on-disk manifest transitively, version-checking every declared peer. Raises on any failure. + acc:`visited`fails!(`symbol$();()); + raisefails (({[acc;e] visitversion[acc;e]}/[acc;entries])`fails) + }; + +readmanifestfile:{[path] + / read a deps.toml FILE at an explicit path (an app-level or custom-process manifest, not a module dir) into its + / [dependencies] dict. Absent file, or no [dependencies] section -> empty dict (the opt-in "nothing declared" case). + probe:hsym `$path; + if[0=count key probe;:()!()]; + d:(resolvetoml[])[`parsefile] path; + $[`dependencies in key d;d`dependencies;()!()] + }; + +checkversiongraphfile:{[requiringmod;manifestpath] + / PRE-LOAD version graph rooted at a manifest FILE (the app's own deps.toml, or a custom process's + / code/processes/.deps.toml): version-check its declared deps, then walk into each. Absent file -> no-op. + deps:readmanifestfile manifestpath; + acc:`visited`fails!(`symbol$();()); + acc[`fails]:raze checkinstalledversion[requiringmod;;]'[key deps;value deps]; + raisefails (({[acc;dep] visitversion[acc;dep]}/[acc;key deps])`fails) + }; + / ============================================================ / core dependency contract checks / ============================================================ @@ -310,7 +423,7 @@ checkgraph:{[] checkcontract:{[provider;requiredkeys] requiredkeys:$[-11h=type requiredkeys;enlist requiredkeys;requiredkeys]; sn:shortmod provider; - vns:modvendorns provider; + vns:modparentns provider; if[not sn in key vns;:()]; xp:getexport provider; if[xp~(::);:enlist string[provider]," is loaded but its export dict could not be read"]; @@ -319,7 +432,7 @@ checkcontract:{[provider;requiredkeys] }; checkcontracts:{[] - / checks whichever of the known core-dependency providers (di.log/di.timer/di.handlers) are loaded in this session + / checks whichever of the known core-dependency providers (di.util.log/di.timer/di.torq.handlers) are loaded in this session raze checkcontract'[key contracts;value contracts] }; @@ -331,9 +444,9 @@ ztscheck:{[] / warns if .z.ts is bound to something while di.timer either isn't loaded or doesn't look initialised / LIMITATION (accepted, warning-level only): di.timer's `enabled` flag being 1b is evidence its init ran and bound / .z.ts itself - it does NOT prove nothing has overwritten .z.ts since. di.timer assigns .z.ts directly (not via - / di.handlers, which explicitly excludes .z.ts from its own scope), so there is no ownership marker to check + / di.torq.handlers, which explicitly excludes .z.ts from its own scope), so there is no ownership marker to check / instead. Scope is deliberately limited to .z.ts only - whether this should ever cover other .z.* events is an - / open question for di.handlers' owner, not decided here + / open question for di.torq.handlers' owner, not decided here bound:not (::)~@[get;`.z.ts;{(::)}]; if[not bound;:()]; timerowns:(`0timer in key `.m.di) and 1b~@[get;`.m.di.0timer.enabled;0b]; @@ -350,7 +463,7 @@ kdbxcheck:{[deps] / uses .z.K, matching di.k4unit's own precedent (`minver<=.z.K` gates which tests run) rather than parsing .z.v, / whose value on this box ("5.0.20260122") did not match the plan's assumed kdb-x product-semver shape and isn't / confirmed to be the same number as the product version shown in the kdb-x startup banner - see depcheck.md - / warning-level, not fail-fast: there is no config cascade yet for di.depcheck to source a minimum from, so this + / warning-level, not fail-fast: there is no config cascade yet for di.torq.depcheck to source a minimum from, so this / is opt-in via an extra key on the same `deps dict rather than a new config channel minversion:$[`minkdbxversion in key deps;deps`minkdbxversion;0Nf]; if[null minversion;:()]; @@ -372,15 +485,15 @@ buildreport:{[header;lines] / ============================================================ init:{[deps] - / initialise di.depcheck - validate the required log dependency, then audit the current session: dependency + / initialise di.torq.depcheck - validate the required log dependency, then audit the current session: dependency / presence/version, core-dependency-contract shape, .z.ts ownership, and (optionally) a minimum kdb-x engine / version. deps: a dict with a required `log key (binary `info`warn`error functions, per consistency.md) and an / optional `minkdbxversion float - if[99h<>type deps;'"di.depcheck: deps must be a dict with `log key"]; - if[not `log in key deps;'"di.depcheck: log dependency is required; pass `info`warn`error functions - see di.log"]; - if[99h<>type deps`log;'"di.depcheck: log value must be a dict; pass `info`warn`error functions"]; + if[99h<>type deps;'"di.torq.depcheck: deps must be a dict with `log key"]; + if[not `log in key deps;'"di.torq.depcheck: log dependency is required; pass `info`warn`error functions - see di.util.log"]; + if[99h<>type deps`log;'"di.torq.depcheck: log value must be a dict; pass `info`warn`error functions"]; if[not all `info`warn`error in key deps`log; - '"di.depcheck: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + '"di.torq.depcheck: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; .z.m.loginfo:(deps`log)`info; .z.m.logwarn:(deps`log)`warn; .z.m.logerr:(deps`log)`error; @@ -397,7 +510,7 @@ init:{[deps] if[count failures; report:buildreport["DEPENDENCY CHECK FAILED";failures]; .z.m.logerr[`depcheck;report]; - '"di.depcheck: ",report]; + '"di.torq.depcheck: ",report]; .z.m.loginfo[`depcheck;"dependency check complete: ",(string count failures)," failure(s), ",(string count warnings)," warning(s)"]; }; diff --git a/di/torq/depcheck/deps.q b/di/torq/depcheck/deps.q new file mode 100644 index 00000000..9ee55787 --- /dev/null +++ b/di/torq/depcheck/deps.q @@ -0,0 +1,4 @@ +/ hard module dependencies and their minimum versions, validated by di.torq.depcheck +/ di.torq.depcheck has no hard dependencies - its only runtime dependency (log) is injected via init as a dictionary of +/ functions, following the same convention di.torq.depcheck itself checks other modules against +deps:(`$())!(); diff --git a/di/torq/depcheck/init.q b/di/torq/depcheck/init.q new file mode 100644 index 00000000..984c1cc5 --- /dev/null +++ b/di/torq/depcheck/init.q @@ -0,0 +1,8 @@ +/ di.torq.depcheck - dependency presence/version, core-contract, and .z.ts ownership auditing for kdb-x modules +/ intended to run once, post-load, after a host process (di.torq) has `use`d every module it needs - see depcheck.md + +\l ::depcheck.q + +version:first read0`:::VERSION + +export:([init;version;checkcontract;checkversiongraph;checkversiongraphfile]) diff --git a/di/torq/depcheck/test.csv b/di/torq/depcheck/test.csv new file mode 100644 index 00000000..83f10a11 --- /dev/null +++ b/di/torq/depcheck/test.csv @@ -0,0 +1,217 @@ +action,ms,bytes,lang,code,repeat,minver,comment +comment,,,,,,,setup - load module and a capturing logger +before,0,0,q,depcheck:use`di.torq.depcheck,1,,load di.torq.depcheck module +before,0,0,q,.dc.captbl:([]lvl:`symbol$();ctx:`symbol$();msg:()),1,,log capture table for assertions +before,0,0,q,caplog:`info`warn`error!({[c;m] `.dc.captbl insert (`info;c;m)};{[c;m] `.dc.captbl insert (`warn;c;m)};{[c;m] `.dc.captbl insert (`error;c;m)}),1,,capturing binary logger {[c;m]} + +comment,,,,,,,init - dependency validation +fail,0,0,q,depcheck.init[(::)],1,,init rejects a non-dict deps +fail,0,0,q,depcheck.init[()!()],1,,init rejects missing log key +fail,0,0,q,depcheck.init[enlist[`log]!enlist 42],1,,init rejects a non-dict log value +fail,0,0,q,depcheck.init[enlist[`log]!enlist `info`warn!(caplog`info;caplog`warn)],1,,init rejects a log dict missing the error key +run,0,0,q,.dc.errstr:@[{depcheck.init[()!()]};(::);{x}],1,,capture the error string from a bad init +true,0,0,q,.dc.errstr like "di.torq.depcheck:*",1,,init error is prefixed di.torq.depcheck: + +comment,,,,,,,module metadata - exported version +true,0,0,q,10h=type depcheck.version,1,,version is a string +true,0,0,q,0 zzgb (installed on QPATH) -> zzgc (absent). +comment,,,,,,,zzgb also declares zzga (a cycle), which the visited-set guard must terminate. zzgb itself is a direct dep +comment,,,,,,,of the loaded root so it is checkdeps' domain and must NOT be double-reported by checkgraph +run,0,0,q,.m.di.0zzga.export:([]),1,,fabricate a loaded module di.zzga so it becomes a walk root +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzga "",.dc.qr,""/di/zzgb""; (hsym `$.dc.qr,""/di/zzga/init.q"") 0: enlist ""export:([])""; (hsym `$.dc.qr,""/di/zzga/deps.q"") 0: enlist ""deps:enlist[`di.zzgb]!enlist \""1.0.0\""""",1,,install zzga on QPATH declaring zzgb +run,0,0,q,"(hsym `$.dc.qr,""/di/zzgb/init.q"") 0: enlist ""export:([])""; (hsym `$.dc.qr,""/di/zzgb/deps.q"") 0: enlist ""deps:`di.zzgc`di.zzga!(\""1.0.0\"";\""1.0.0\"")""",1,,install zzgb on QPATH declaring zzgc (missing) and zzga (cycle) +true,0,0,q,"any (.m.di.0torq.0depcheck.checkgraph[]) like ""di.zzgc is required transitively by di.zzgb*""",1,,checkgraph surfaces a depth>=2 dependency that does not resolve on QPATH +true,0,0,q,"not any (.m.di.0torq.0depcheck.checkgraph[]) like ""di.zzgb is required transitively*""",1,,zzgb (a direct dep of the loaded root) is not double-reported - the cycle also terminated without error +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzga "",.dc.qr,""/di/zzgb""",1,,remove the graph-walk on-disk fixtures (the fabricated .m.di.0zzga is harmless with no deps on disk) + +comment,,,,,,,resolvemodule - QPATH presence resolution without loading, distinct from checkonedep's loaded-check +true,0,0,q,not (::)~.m.di.0torq.0depcheck.resolvemodule `di.timer,1,,a real installed module resolves on QPATH +true,0,0,q,(::)~.m.di.0torq.0depcheck.resolvemodule `di.doesnotexistanywhere,1,,an absent module resolves to (::) + +comment,,,,,,,a deps.toml that exists but declares no [dependencies] section - the else branch of readdepstoml +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zznodeps""; (hsym `$.dc.qr,""/di/zznodeps/deps.toml"") 0: enlist ""name = \""foo\""""",1,,create a deps.toml with a top-level key but no [dependencies] section +true,0,0,q,0=count (.m.di.0torq.0depcheck.readdeps `di.zznodeps) 1,1,,a deps.toml with no [dependencies] section yields an empty merged manifest not a crash +true,0,0,q,"$[.dc.havetoml;0=count (.m.di.0torq.0depcheck.readdeps `di.zznodeps) 0;1b]",1,,and no read-failures either - a valid file with nothing declared is not an error (needs di.util.toml to read the file; no-op pass when absent) +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zznodeps""",1,,remove the no-dependencies scratch fixture + +comment,,,,,,,malformed [dependencies] - a deps.toml where `dependencies` is a scalar not a section. must degrade to a +comment,,,,,,,clean failure line with an empty merged dict, NOT throw out of readdeps's merge and abort the whole walk +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzscalar""; (hsym `$.dc.qr,""/di/zzscalar/deps.toml"") 0: enlist ""dependencies = \""oops\""""",1,,create a deps.toml whose dependencies key is a scalar string +true,0,0,q,"$[.dc.havetoml;any ((.m.di.0torq.0depcheck.readdeps `di.zzscalar) 0) like ""di.torq.depcheck: deps.toml for di.zzscalar has a malformed*"";1b]",1,,a non-dict [dependencies] is reported as one clear failure line (no-op pass when di.util.toml is absent) +true,0,0,q,0=count (.m.di.0torq.0depcheck.readdeps `di.zzscalar) 1,1,,and the merged manifest is empty so the merge never throws +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzscalar""",1,,remove the malformed-dependencies scratch fixture + +comment,,,,,,,non-string version value - an unquoted deps.toml version parses to a float; a deps.q version may be an int +comment,,,,,,,or symbol. either is an authoring error reported as its own clear line, never a corrupted concatenated +comment,,,,,,,message or a throw out of parsesemver's `vs`. a single-char string version must NOT trip this guard +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzfloatver""; (hsym `$.dc.qr,""/di/zzfloatver/deps.toml"") 0: (""[dependencies]"";""\""di.timer\"" = 1.0"")",1,,deps.toml with an UNQUOTED version - di.util.toml parses it as a float +true,0,0,q,"$[.dc.havetoml;any (.m.di.0torq.0depcheck.checkmoduledeps `di.zzfloatver) like ""di.timer has a non-string minimum version*"";1b]",1,,an unquoted (float) deps.toml version is reported as a non-string version, not a garbage line or a crash (needs di.util.toml to parse the float; no-op pass when absent) +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzfloatver""",1,,remove the float-version fixture +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzintver""; (hsym `$.dc.qr,""/di/zzintver/deps.q"") 0: enlist ""deps:enlist[`di.timer]!enlist 5""",1,,deps.q with an int version value +true,0,0,q,"any (.m.di.0torq.0depcheck.checkmoduledeps `di.zzintver) like ""di.timer has a non-string minimum version*""",1,,an int deps.q version is reported as a non-string version too +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzintver""",1,,remove the int-version fixture +run,0,0,q,"system ""mkdir -p "",.dc.qr,""/di/zzonechar""; (hsym `$.dc.qr,""/di/zzonechar/deps.q"") 0: enlist ""deps:enlist[`di.timer]!enlist \""1\""""",1,,deps.q with a legitimate single-char string version +true,0,0,q,"not any (.m.di.0torq.0depcheck.checkmoduledeps `di.zzonechar) like ""di.timer has a non-string minimum*""",1,,a single-char string version is valid and must NOT be flagged as non-string - the guard does not over-trigger +run,0,0,q,"system ""rm -rf "",.dc.qr,""/di/zzonechar""",1,,remove the single-char-version fixture + +comment,,,,,,,pre-load VERSION graph (grafted from TorqX) - on-disk resolvemodule + VERSION-file transitive version check +run,0,0,q,".dc.vg:first "":"" vs getenv`QPATH",1,,scratch QPATH root for the pre-load version-graph fixtures +run,0,0,q,"{[r;d] system ""mkdir -p "",r,""/di/"",d; (hsym `$r,""/di/"",d,""/init.q"") 0: enlist ""export:([])""}[.dc.vg;] each (""vgok"";""vgbad"";""vgmid"";""vgleaf"";""vgroot"")",1,,five installable fixture modules (each needs an init.q to resolve on QPATH) +run,0,0,q,"(hsym `$.dc.vg,""/di/vgok/VERSION"") 0: enlist ""2.0.0""",1,,vgok installed at 2.0.0 +run,0,0,q,"(hsym `$.dc.vg,""/di/vgbad/VERSION"") 0: enlist ""1.0.0""",1,,vgbad installed at 1.0.0 +run,0,0,q,"(hsym `$.dc.vg,""/di/vgleaf/VERSION"") 0: enlist ""1.0.0""",1,,vgleaf installed at 1.0.0 +run,0,0,q,"(hsym `$.dc.vg,""/di/vgmid/VERSION"") 0: enlist ""1.0.0""",1,,vgmid installed at 1.0.0 +run,0,0,q,"(hsym `$.dc.vg,""/di/vgmid/deps.q"") 0: enlist ""deps:enlist[`di.vgleaf]!enlist \""9.9.9\""""",1,,vgmid declares di.vgleaf>=9.9.9 (unsatisfiable - vgleaf is 1.0.0) +run,0,0,q,"(hsym `$.dc.vg,""/di/vgroot/deps.q"") 0: enlist ""deps:`di.vgok`di.vgmid!(\""1.0.0\"";\""1.0.0\"")""",1,,vgroot declares vgok+vgmid (both satisfied at the root; the transitive fault is under vgmid) +true,0,0,q,"""2.0.0""~.m.di.0torq.0depcheck.readversion .m.di.0torq.0depcheck.resolvemodule `di.vgok",1,,readversion reads a resolved module's on-disk VERSION file without loading it +true,0,0,q,0=count .m.di.0torq.0depcheck.checkinstalledversion[`;`di.vgok;"1.0.0"],1,,an installed dependency whose VERSION meets the minimum passes +true,0,0,q,".m.di.0torq.0depcheck.checkinstalledversion[`;`di.vgbad;""2.0.0""]~enlist ""di.vgbad requires minimum version 2.0.0, found 1.0.0""",1,,an installed dependency below the minimum reports its found version +true,0,0,q,"any .m.di.0torq.0depcheck.checkinstalledversion[`;`di.doesnotexistanywhere;""1.0.0""] like ""*not found on QPATH""",1,,an uninstalled dependency is reported not found (pre-load presence) +true,0,0,q,(()!())~depcheck.checkversiongraph[enlist `di.vgok],1,,a leaf entry with no manifest passes cleanly +true,0,0,q,(()!())~depcheck.checkversiongraph[enlist `di.vgleaf],1,,a satisfied subtree passes +true,0,0,q,"(@[depcheck.checkversiongraph;enlist `di.vgroot;{x}]) like ""*(required by di.vgmid) di.vgleaf requires minimum version 9.9.9, found 1.0.0*""",1,,a transitive (depth-2) version mismatch is caught pre-load and attributed to the module that imposed it +run,0,0,q,"(hsym `$.dc.vg,""/passmanifest.toml"") 0: (""[dependencies]"";""\""di.vgok\"" = \""1.0.0\"""")",1,,an app-level manifest file satisfied by what is installed +run,0,0,q,"(hsym `$.dc.vg,""/failmanifest.toml"") 0: (""[dependencies]"";""\""di.vgbad\"" = \""2.0.0\"""")",1,,an app-level manifest file NOT satisfied (vgbad is 1.0.0) +true,0,0,q,"$[.dc.havetoml;(()!())~depcheck.checkversiongraphfile[`;.dc.vg,""/passmanifest.toml""];1b]",1,,a satisfied app manifest FILE passes (no-op pass if di.util.toml is absent) +true,0,0,q,"$[.dc.havetoml;(@[depcheck.checkversiongraphfile[`;];.dc.vg,""/failmanifest.toml"";{x}]) like ""*di.vgbad requires minimum version 2.0.0, found 1.0.0*"";1b]",1,,an unsatisfied app manifest FILE is caught pre-load (no-op pass if di.util.toml is absent) +true,0,0,q,"(()!())~depcheck.checkversiongraphfile[`;.dc.vg,""/nonexistent.toml""]",1,,an absent manifest file is a clean no-op (opt-in) +run,0,0,q,"system ""rm -rf "",.dc.vg,""/di/vgok "",.dc.vg,""/di/vgbad "",.dc.vg,""/di/vgmid "",.dc.vg,""/di/vgleaf "",.dc.vg,""/di/vgroot""; system ""rm -f "",.dc.vg,""/passmanifest.toml "",.dc.vg,""/failmanifest.toml""",1,,remove the version-graph fixtures diff --git a/di/depcheck/test_integration.csv b/di/torq/depcheck/test_integration.csv similarity index 85% rename from di/depcheck/test_integration.csv rename to di/torq/depcheck/test_integration.csv index 4c9a63f0..bdb4f865 100644 --- a/di/depcheck/test_integration.csv +++ b/di/torq/depcheck/test_integration.csv @@ -14,8 +14,8 @@ before,0,0,q,.it.haveqbin:not ()~key hsym `$qbin,1,,confirm the resolved binary before,0,0,q,if[not .it.haveqbin;exit 0],1,,skip this entire suite cleanly if the binary could not be resolved before,0,0,q,".it.dir:(first "":"" vs getenv`QPATH),""/di/zzintegration""",1,,scratch directory derived from QPATH at runtime - no hardcoded path before,0,0,q,"system ""mkdir -p "",.it.dir",1,,create the scratch directory -before,0,0,q,"(hsym `$.it.dir,""/success.q"") 0: enlist ""depcheck:use`di.depcheck; logdep:`info`warn`error!({[c;m] -1 m};{[c;m] -1 m};{[c;m] -2 m}); depcheck.init[enlist[`log]!enlist logdep]; exit 0;""",1,,"write a real child script loading ONLY di.depcheck - no di.timer, so no real contract gap exists - a genuine zero-failure success case" -before,0,0,q,"(hsym `$.it.dir,""/failure.q"") 0: enlist ""timer:use`di.timer; depcheck:use`di.depcheck; logdep:`info`warn`error!({[c;m] -1 m};{[c;m] -1 m};{[c;m] -2 m}); depcheck.init[enlist[`log]!enlist logdep]; exit 0;""",1,,"write a real child script that also loads di.timer - its real, permanent Timer-contract gap (missing cp) drives a real failure" +before,0,0,q,"(hsym `$.it.dir,""/success.q"") 0: enlist ""depcheck:use`di.torq.depcheck; logdep:`info`warn`error!({[c;m] -1 m};{[c;m] -1 m};{[c;m] -2 m}); depcheck.init[enlist[`log]!enlist logdep]; exit 0;""",1,,"write a real child script loading ONLY di.torq.depcheck - no di.timer, so no real contract gap exists - a genuine zero-failure success case" +before,0,0,q,"(hsym `$.it.dir,""/failure.q"") 0: enlist ""timer:use`di.timer; depcheck:use`di.torq.depcheck; logdep:`info`warn`error!({[c;m] -1 m};{[c;m] -1 m};{[c;m] -2 m}); depcheck.init[enlist[`log]!enlist logdep]; exit 0;""",1,,"write a real child script that also loads di.timer - its real, permanent Timer-contract gap (missing cp) drives a real failure" before,0,0,q,".it.successresult:system qbin,"" "",.it.dir,""/success.q -q < /dev/null > "",.it.dir,""/success.out 2>&1; echo EXITCODE:$?""",1,,"run the success child to completion synchronously, capturing combined stdout+stderr and its real exit code" before,0,0,q,".it.successexit:""I""$9_last .it.successresult",1,,parse the real exit code before,0,0,q,".it.successout:sv[""\n"";read0 hsym `$.it.dir,""/success.out""]",1,,read the child's real captured output @@ -25,7 +25,7 @@ before,0,0,q,".it.failureout:sv[""\n"";read0 hsym `$.it.dir,""/failure.out""]",1 before,0,0,q,"system ""rm -rf "",.it.dir",1,,remove the scratch fixture directory ,,,,,,, comment,,,,,,,genuine zero-failure success path - unreachable in test.csv since di.timer always fails its own contract there -true,0,0,q,0=.it.successexit,1,,the child process loading only di.depcheck exited cleanly with a real 0 exit code +true,0,0,q,0=.it.successexit,1,,the child process loading only di.torq.depcheck exited cleanly with a real 0 exit code true,0,0,q,".it.successout like ""*dependency check complete: 0 failure(s), 0 warning(s)*""",1,,the real captured log shows the genuine zero-failure summary line - proves the true success path works end to end in a real process ,,,,,,, comment,,,,,,,a real signalled failure actually terminates a real host process diff --git a/di/torq/handlers/VERSION b/di/torq/handlers/VERSION new file mode 100644 index 00000000..6c6aa7cb --- /dev/null +++ b/di/torq/handlers/VERSION @@ -0,0 +1 @@ +0.1.0 \ No newline at end of file diff --git a/di/handlers/handlers.md b/di/torq/handlers/handlers.md similarity index 94% rename from di/handlers/handlers.md rename to di/torq/handlers/handlers.md index a219f825..1478c77f 100644 --- a/di/handlers/handlers.md +++ b/di/torq/handlers/handlers.md @@ -1,4 +1,4 @@ -# di.handlers +# di.torq.handlers Central registry for a KDB-X process's `.z.*` connection-lifecycle callbacks — connection open and close, websocket open and close, process exit, and the message, auth and HTTP handlers. It lets multiple independent components hook the same event without silently overwriting one another, and is the single place in a process that assigns `.z.*` directly. @@ -43,16 +43,16 @@ Simple events take a null phase (`` ` ``); phased events take one of `` `pre`exe **No hard dependencies** on other `di.*` modules — the module works standalone. -The `log` dependency is passed to `init` keyed on `` `log ``. It must be a dict containing all three of `info`, `warn`, and `error`: `info` records register/remove activity, `warn` reports an isolated handler that threw during dispatch, and `error` reports a rejected call before it is signalled. `init` throws immediately if `log` is absent, is not a dict, or is missing any key. No adaptation is performed — pass a dict that already conforms to the `{[c;m]}` contract (for example one built from `di.log`). +The `log` dependency is passed to `init` keyed on `` `log ``. It must be a dict containing all three of `info`, `warn`, and `error`: `info` records register/remove activity, `warn` reports an isolated handler that threw during dispatch, and `error` reports a rejected call before it is signalled. `init` throws immediately if `log` is absent, is not a dict, or is missing any key. No adaptation is performed — pass a dict that already conforms to the `{[c;m]}` contract (for example one built from `di.util.log`). --- ## Initialisation ```q -handlers:use`di.handlers +handlers:use`di.torq.handlers -/ a conforming log dict (or one supplied by di.log) +/ a conforming log dict (or one supplied by di.util.log) logdep:`info`warn`error!( {[c;m] -1 string[c],": INFO ",m;}; {[c;m] -1 string[c],": WARN ",m;}; @@ -110,9 +110,9 @@ handlers.version / "0.1.0" ## Usage Example ```q -handlers:use`di.handlers +handlers:use`di.torq.handlers -/ a no-op log dep for illustration (di.log would supply a real one) +/ a no-op log dep for illustration (di.util.log would supply a real one) logdep:`info`warn`error!(3#{[c;m]}); handlers.init[enlist[`log]!enlist logdep] @@ -149,14 +149,14 @@ handlers.remove[`.z.pc;`;`metrics] ```q k4unit:use`di.k4unit -k4unit.moduletest`di.handlers +k4unit.moduletest`di.torq.handlers ``` **Integration suite** (`test_integration.csv`) — stands up a real child q process on an OS-assigned ephemeral port, opens and closes a connection, and confirms a registered `.z.pc` handler actually fired. It needs a q/kdb-x binary reachable via `QHOME`, needs no other configuration, and skips cleanly when no usable binary is available. `moduletest` only ever loads `test.csv`, so load and run this suite directly: ```q k4unit:use`di.k4unit -.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.handlers;`test_integration.csv] +.m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.torq.handlers;`test_integration.csv] .m.di.0k4unit.KUrt[] k4unit.getresults[] / one row per assertion; ok=1 is a pass ``` @@ -170,13 +170,13 @@ Run the integration suite in a fresh q session — running it after `moduletest` - `init` must be called before any other function, and is idempotent. - **Fault isolation is asymmetric.** `pre` and `exec` run unprotected: a throw propagates to the caller, and a `pre` throw is the sanctioned way to veto a request (e.g. an auth rejection). `post` and simple handlers run isolated: a throw is logged at `warn` and cannot change the outcome or stop the other handlers. A broken `pre` blocking its event is an accepted tradeoff — q cannot tell a deliberate veto from a bug, both being a throw. - Priority is an integer, **lower runs first**; handlers at equal priority run in registration order. -- `.z.ph` is a normal phased event, but an `exec` owner on it **replaces the KDB-X built-in HTTP GET handler wholesale** — including the `.h`-namespace response formatting — so the owner becomes fully responsible for the GET response. GET **permissioning** is done via `.h.val` (a `.h` hook, not a `.z.*` callback) and is **not managed by this module**; a `pre` veto on `.z.ph` works but does not substitute for `.h.val`-based permissioning of the default handler. `.z.ph` is the only phased event KDB-X ships a default handler for, and `\x` expunges rather than restores it, so di.handlers captures that shipped handler when the `exec` is claimed and puts it back on `remove` (the other phased events have no shipped default and `\x`-restore correctly). +- `.z.ph` is a normal phased event, but an `exec` owner on it **replaces the KDB-X built-in HTTP GET handler wholesale** — including the `.h`-namespace response formatting — so the owner becomes fully responsible for the GET response. GET **permissioning** is done via `.h.val` (a `.h` hook, not a `.z.*` callback) and is **not managed by this module**; a `pre` veto on `.z.ph` works but does not substitute for `.h.val`-based permissioning of the default handler. `.z.ph` is the only phased event KDB-X ships a default handler for, and `\x` expunges rather than restores it, so di.torq.handlers captures that shipped handler when the `exec` is claimed and puts it back on `remove` (the other phased events have no shipped default and `\x`-restore correctly). - `.z.pw` is binary and supports `exec` and `post` only — there is no `pre` phase. The `exec` owner sees the real `(user;password)`; `post` handlers see `(user;"***")`, so only the owner ever sees the password. - A `post` handler's `args` is the argument list `exec` was invoked with, **except that `.z.pw`'s password is deliberately redacted** — `exec` sees the real `(user;password)`, `post` sees `(user;"***")`, so a `post` handler can never read a real password. That asymmetry is intentional, not an oversight: it is what lets an audit-log `post` handler exist on `.z.pw` at all. For the six unary phased events `args` is `enlist request` — the request *after* any `pre` reshaped it, not the original caller's input — paired with the `result` that request produced. `.z.pw` has no `pre` phase, so its request is never transformed. - A `post` handler runs synchronously after the owner and before its result is returned, so it adds to that event's response time — unlike simple-event handlers, where nothing awaits the return. -- A `post` handler runs in the event's own execution context; under multithreaded input (a negative `\p` port) that is not the main thread, so a `post` that writes a global hits kdb's `'noupdate` restriction, as any `.z.pg` code would. di.handlers' own dispatch only reads its registries and is unaffected. +- A `post` handler runs in the event's own execution context; under multithreaded input (a negative `\p` port) that is not the main thread, so a `post` that writes a global hits kdb's `'noupdate` restriction, as any `.z.pg` code would. di.torq.handlers' own dispatch only reads its registries and is unaffected. - `.z.ts` is not managed here — it belongs to `di.timer`. - The handler bound to a simple event before its first registration is captured once and always runs last, after every registered handler. - Removing the `exec` owner restores the KDB-X built-in default (via `\x` for every phased event except `.z.ph`, whose shipped handler is captured and put back — see the `.z.ph` note above), not any handler that happened to be bound before the module took ownership. -- Removing a simple handler drops it from the fan-out, but the event's dispatcher — installed once on first registration — stays installed permanently; removing the last handler does not revert the event, which keeps running an empty fan-out plus the captured original. Unlike a phased event (whose `exec` `remove` restores the KDB-X built-in default — see the removal bullet above), a simple event has no path back to its pre-di.handlers binding. +- Removing a simple handler drops it from the fan-out, but the event's dispatcher — installed once on first registration — stays installed permanently; removing the last handler does not revert the event, which keeps running an empty fan-out plus the captured original. Unlike a phased event (whose `exec` `remove` restores the KDB-X built-in default — see the removal bullet above), a simple event has no path back to its pre-di.torq.handlers binding. - All errors raised after `init` are logged at `error` before being signalled. diff --git a/di/handlers/handlers.q b/di/torq/handlers/handlers.q similarity index 67% rename from di/handlers/handlers.q rename to di/torq/handlers/handlers.q index e34163b6..f343048d 100644 --- a/di/handlers/handlers.q +++ b/di/torq/handlers/handlers.q @@ -1,9 +1,10 @@ / central registry for KDB-X .z.* connection-lifecycle callbacks / the single sanctioned place to hook .z.* events - replaces per-file hand-rolled closure wrapping -/ simple events fan out to any number of registrants; phased events thread pre -> exec -> post around one owner +/ simple events fan out to any number of registrants; phased events thread pre -> exec -> transform -> post around one owner -/ module version - placeholder only; no project-wide version / di.depcheck convention exists yet -version:"0.1.0"; +/ version is read from the VERSION file (init.q); di.torq.depcheck reads that file for the manifest graph +/ NOTE: `transform` phase (chained result rewrite between exec and post) is a TorqX addition on top +/ of the upstream feature-handlers design - see docs/reconciliation/handlers.md. Fed back to that PR. / ============================================================ / constants (load-time) @@ -12,7 +13,7 @@ version:"0.1.0"; / simple events - KDB-X discards the return value, so any number of side-effect-only handlers can coexist (phase must be `) observerevents:`.z.pc`.z.po`.z.exit`.z.wo`.z.wc; -/ phased events - pre (transform request) -> exec (single owner produces the outcome) -> post (side-effect watchers) +/ phased events - pre (transform request) -> exec (single owner) -> transform (rewrite result) -> post (observe) / .z.pw is included but binary and pre-less (see register); .z.ph replaces the built-in HTTP GET handler wholesale (see notes) phasedevents:`.z.pg`.z.ps`.z.pi`.z.pp`.z.ph`.z.ws`.z.pw; @@ -95,10 +96,13 @@ runpostall:{[event;result;args] }; dispatchphased:{[event;req] - / thread the request through pre (transform, unprotected) -> exec owner (unprotected) -> post (observe, protected) + / thread the request through pre (transform, unprotected) -> exec owner (unprotected) -> transform + / (rewrite result, chained, unprotected) -> post (observe, protected) pres:exec func from `priority xasc .z.m.pre event; req:{[acc;f] f acc}/[req;pres]; r:.z.m.ownerfunc[event] req; + xforms:exec func from `priority xasc .z.m.transform event; + r:{[acc;f] f acc}/[r;xforms]; runpostall[event;r;enlist req]; r }; @@ -106,6 +110,8 @@ dispatchphased:{[event;req] dispatchpw:{[u;p] / .z.pw is the only binary phased event - the owner sees the real password; post handlers see it redacted to "***"; no pre r:.z.m.ownerfunc[`.z.pw][u;p]; + xforms:exec func from `priority xasc .z.m.transform `.z.pw; + r:{[acc;f] f acc}/[r;xforms]; runpostall[`.z.pw;r;(u;"***")]; r }; @@ -115,6 +121,7 @@ installphased:{[event] / .z.ph is the only phased event KDB-X ships a default handler for, and \x cannot restore it - capture it to put back on remove if[event~`.z.ph;.z.m.original[event]:@[value;event;{(::)}]]; .z.m.pre[event]:phasetableschema; + .z.m.transform[event]:phasetableschema; .z.m.post[event]:phasetableschema; set[event;$[event~`.z.pw;dispatchpw;dispatchphased[event;]]]; }; @@ -123,7 +130,7 @@ registerexec:{[event;nm;pri;func] / single owner - a different name claiming an owned event is rejected; the same name reclaims (idempotent re-init) if[event in key .z.m.owner; if[not nm~.z.m.owner event; - .z.m.logerr[`register;err:"di.handlers: ",string[event]," already owned by ",string[.z.m.owner event]," - call remove first"];'err]]; + .z.m.logerr[`register;err:"di.torq.handlers: ",string[event]," already owned by ",string[.z.m.owner event]," - call remove first"];'err]]; .z.m.owner[event]:nm; / update the owner function in place if the dispatcher is installed (it reads ownerfunc fresh), else install on first exec .z.m.ownerfunc[event]:func; @@ -132,21 +139,26 @@ registerexec:{[event;nm;pri;func] .z.m.loginfo[`register;"registered exec owner ",string[nm]," on ",string[event]]; }; +/ the three satellite phases (pre/transform/post) all key their own registry table by event; pick it by phase +satellitetable:{[phase] $[phase~`pre;.z.m.pre;phase~`transform;.z.m.transform;.z.m.post]}; + registerprepost:{[event;phase;nm;pri;func] - / pre/post cannot attach before an exec owner exists - the dispatcher is only live once exec is registered + / pre/transform/post cannot attach before an exec owner exists - the dispatcher is only live once exec is registered if[not event in key .z.m.ownerfunc; - .z.m.logerr[`register;err:"di.handlers: cannot register ",string[phase]," on ",string[event]," before an exec owner exists - register the exec phase first"];'err]; + .z.m.logerr[`register;err:"di.torq.handlers: cannot register ",string[phase]," on ",string[event]," before an exec owner exists - register the exec phase first"];'err]; $[phase~`pre;.z.m.pre[event]:upsertphase[.z.m.pre event;nm;pri;func]; + phase~`transform;.z.m.transform[event]:upsertphase[.z.m.transform event;nm;pri;func]; .z.m.post[event]:upsertphase[.z.m.post event;nm;pri;func]]; .z.m.loginfo[`register;"registered ",string[phase]," handler ",string[nm]," on ",string[event]]; }; removeprepost:{[event;phase;nm] - / drop a pre or post handler; the dispatcher stays installed regardless of remaining count - tbl:$[phase~`pre;.z.m.pre;.z.m.post]; + / drop a pre/transform/post handler; the dispatcher stays installed regardless of remaining count + tbl:satellitetable phase; if[not event in key tbl;.z.m.loginfo[`remove;"no ",string[phase]," handlers on ",string[event],"; nothing to remove for ",string[nm]];:(::)]; if[not nm in exec name from tbl event;.z.m.loginfo[`remove;string[phase]," handler ",string[nm]," not registered on ",string[event],"; nothing to remove"];:(::)]; $[phase~`pre;.z.m.pre[event]:delete from .z.m.pre event where name=nm; + phase~`transform;.z.m.transform[event]:delete from .z.m.transform event where name=nm; .z.m.post[event]:delete from .z.m.post event where name=nm]; .z.m.loginfo[`remove;"removed ",string[phase]," handler ",string[nm]," on ",string[event]]; }; @@ -155,7 +167,7 @@ removeexec:{[event;nm] / relinquish ownership only if this name owns it, restore the KDB-X default, and clear all phased state for the event if[not event in key .z.m.owner;.z.m.loginfo[`remove;"no exec owner on ",string[event],"; nothing to remove for ",string[nm]];:(::)]; if[not nm~.z.m.owner event; - .z.m.logerr[`remove;err:"di.handlers: ",string[event]," is owned by ",string[.z.m.owner event],", not ",string[nm]];'err]; + .z.m.logerr[`remove;err:"di.torq.handlers: ",string[event]," is owned by ",string[.z.m.owner event],", not ",string[nm]];'err]; / .z.ph ships a default handler that \x expunges rather than restores, so put the captured original back; every other phased event \x-restores its built-in default $[(event in key .z.m.original) and not (::)~.z.m.original event;set[event;.z.m.original event];system"x ",string[event]]; .z.m.owner:.z.m.owner _ event; @@ -163,16 +175,18 @@ removeexec:{[event;nm] .z.m.ownerpri:.z.m.ownerpri _ event; .z.m.original:.z.m.original _ event; .z.m.pre:.z.m.pre _ event; + .z.m.transform:.z.m.transform _ event; .z.m.post:.z.m.post _ event; .z.m.loginfo[`remove;"removed exec owner ",string[nm]," on ",string[event],"; restored default"]; }; phasedlist:{[event] - / uniform ([]phase;name;priority) view - pre rows (priority order), the exec owner, then post rows (priority order) + / uniform ([]phase;name;priority) view in dispatch order - pre rows, the exec owner, transform rows, then post rows pre:select phase:`pre,name,priority from `priority xasc .z.m.pre event; + xform:select phase:`transform,name,priority from `priority xasc .z.m.transform event; post:select phase:`post,name,priority from `priority xasc .z.m.post event; owner:([]phase:enlist `exec;name:enlist .z.m.owner event;priority:enlist .z.m.ownerpri event); - pre,owner,post + pre,owner,xform,post }; / ============================================================ @@ -180,57 +194,57 @@ phasedlist:{[event] / ============================================================ register:{[event;phase;nm;pri;func] - / register a handler for a .z.* event - phase is ` for simple events, one of `pre`exec`post for phased events - if[not -11h=type event;.z.m.logerr[`register;err:"di.handlers: event must be a symbol"];'err]; - if[not -11h=type phase;.z.m.logerr[`register;err:"di.handlers: phase must be a symbol (` for simple, `pre`exec`post for phased)"];'err]; - if[not -11h=type nm;.z.m.logerr[`register;err:"di.handlers: name must be a symbol"];'err]; - if[not type[pri] within -7 -5h;.z.m.logerr[`register;err:"di.handlers: priority must be an integer"];'err]; - if[not type[func] within 100 112h;.z.m.logerr[`register;err:"di.handlers: func must be a function"];'err]; + / register a handler for a .z.* event - phase is ` for simple events, one of `pre`exec`transform`post for phased events + if[not -11h=type event;.z.m.logerr[`register;err:"di.torq.handlers: event must be a symbol"];'err]; + if[not -11h=type phase;.z.m.logerr[`register;err:"di.torq.handlers: phase must be a symbol (` for simple, `pre`exec`transform`post for phased)"];'err]; + if[not -11h=type nm;.z.m.logerr[`register;err:"di.torq.handlers: name must be a symbol"];'err]; + if[not type[pri] within -7 -5h;.z.m.logerr[`register;err:"di.torq.handlers: priority must be an integer"];'err]; + if[not type[func] within 100 112h;.z.m.logerr[`register;err:"di.torq.handlers: func must be a function"];'err]; pri:"j"$pri; $[event in observerevents; - [if[not null phase;.z.m.logerr[`register;err:"di.handlers: ",string[event]," is a simple event - phase must be ` (null)"];'err]; + [if[not null phase;.z.m.logerr[`register;err:"di.torq.handlers: ",string[event]," is a simple event - phase must be ` (null)"];'err]; registersimple[event;nm;pri;func]]; event in phasedevents; - [if[not phase in `pre`exec`post;.z.m.logerr[`register;err:"di.handlers: ",string[event]," is a phased event - phase must be one of `pre`exec`post"];'err]; - if[(event~`.z.pw) and phase~`pre;.z.m.logerr[`register;err:"di.handlers: .z.pw has no pre phase - register exec (owner, real password) or post (redacted watcher)"];'err]; + [if[not phase in `pre`exec`transform`post;.z.m.logerr[`register;err:"di.torq.handlers: ",string[event]," is a phased event - phase must be one of `pre`exec`transform`post"];'err]; + if[(event~`.z.pw) and phase~`pre;.z.m.logerr[`register;err:"di.torq.handlers: .z.pw has no pre phase - register exec (owner, real password), transform (rewrite result), or post (redacted watcher)"];'err]; $[phase~`exec;registerexec[event;nm;pri;func];registerprepost[event;phase;nm;pri;func]]]; - [.z.m.logerr[`register;err:"di.handlers: unsupported event ",string[event]];'err]]; + [.z.m.logerr[`register;err:"di.torq.handlers: unsupported event ",string[event]];'err]]; }; remove:{[event;phase;nm] / remove a handler - phase mirrors register; removing an exec restores the KDB-X default and clears the event's phased state - if[not -11h=type event;.z.m.logerr[`remove;err:"di.handlers: event must be a symbol"];'err]; - if[not -11h=type phase;.z.m.logerr[`remove;err:"di.handlers: phase must be a symbol"];'err]; - if[not -11h=type nm;.z.m.logerr[`remove;err:"di.handlers: name must be a symbol"];'err]; + if[not -11h=type event;.z.m.logerr[`remove;err:"di.torq.handlers: event must be a symbol"];'err]; + if[not -11h=type phase;.z.m.logerr[`remove;err:"di.torq.handlers: phase must be a symbol"];'err]; + if[not -11h=type nm;.z.m.logerr[`remove;err:"di.torq.handlers: name must be a symbol"];'err]; $[event in observerevents; - [if[not null phase;.z.m.logerr[`remove;err:"di.handlers: ",string[event]," is a simple event - phase must be ` (null)"];'err]; + [if[not null phase;.z.m.logerr[`remove;err:"di.torq.handlers: ",string[event]," is a simple event - phase must be ` (null)"];'err]; removesimple[event;nm]]; event in phasedevents; - [if[not phase in `pre`exec`post;.z.m.logerr[`remove;err:"di.handlers: ",string[event]," is a phased event - phase must be one of `pre`exec`post"];'err]; + [if[not phase in `pre`exec`transform`post;.z.m.logerr[`remove;err:"di.torq.handlers: ",string[event]," is a phased event - phase must be one of `pre`exec`transform`post"];'err]; $[phase~`exec;removeexec[event;nm];removeprepost[event;phase;nm]]]; - [.z.m.logerr[`remove;err:"di.handlers: unsupported event ",string[event]];'err]]; + [.z.m.logerr[`remove;err:"di.torq.handlers: unsupported event ",string[event]];'err]]; }; list:{[event] / return the registered handlers for a single event as a ([]phase;name;priority) table - if[not -11h=type event;.z.m.logerr[`list;err:"di.handlers: event must be a symbol"];'err]; + if[not -11h=type event;.z.m.logerr[`list;err:"di.torq.handlers: event must be a symbol"];'err]; :$[event in observerevents; simplelist event; event in phasedevents; $[event in key .z.m.owner;phasedlist event;emptylist]; - [.z.m.logerr[`list;err:"di.handlers: unsupported event ",string[event]];'err]]; + [.z.m.logerr[`list;err:"di.torq.handlers: unsupported event ",string[event]];'err]]; }; init:{[deps] - / initialise di.handlers - validate the required log dependency and set up empty registries (idempotent) + / initialise di.torq.handlers - validate the required log dependency and set up empty registries (idempotent) / deps: a dict with a `log key; log must be a dict of binary {[c;m]} functions with `info`warn`error keys / example: handlers.init[enlist[`log]!enlist logdep] if[99h<>type deps; - '"di.handlers: deps must be a dict with `log key"]; + '"di.torq.handlers: deps must be a dict with `log key"]; if[not `log in key deps; - '"di.handlers: log dependency is required; pass `info`warn`error functions keyed on `log"]; + '"di.torq.handlers: log dependency is required; pass `info`warn`error functions keyed on `log"]; if[99h<>type deps`log; - '"di.handlers: log value must be a dict; pass `info`warn`error functions"]; + '"di.torq.handlers: log value must be a dict; pass `info`warn`error functions"]; if[not all `info`warn`error in key deps`log; - '"di.handlers: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + '"di.torq.handlers: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; .z.m.loginfo:(deps`log)`info; .z.m.logwarn:(deps`log)`warn; .z.m.logerr:(deps`log)`error; @@ -242,7 +256,8 @@ init:{[deps] .z.m.ownerfunc:(`$())!(); .z.m.ownerpri:(`$())!(); .z.m.pre:(`$())!(); + .z.m.transform:(`$())!(); .z.m.post:(`$())!(); ]; - .z.m.loginfo[`init;"di.handlers initialised"]; + .z.m.loginfo[`init;"di.torq.handlers initialised"]; }; diff --git a/di/torq/handlers/init.q b/di/torq/handlers/init.q new file mode 100644 index 00000000..bfb70b2c --- /dev/null +++ b/di/torq/handlers/init.q @@ -0,0 +1,7 @@ +/ di.torq.handlers - central registry for KDB-X .z.* connection-lifecycle callbacks + +\l ::handlers.q + +version:first read0`:::VERSION + +export:([init;register;remove;list;version]) diff --git a/di/handlers/test.csv b/di/torq/handlers/test.csv similarity index 83% rename from di/handlers/test.csv rename to di/torq/handlers/test.csv index fa7ea1f5..c7799f80 100644 --- a/di/handlers/test.csv +++ b/di/torq/handlers/test.csv @@ -1,6 +1,6 @@ action,ms,bytes,lang,code,repeat,minver,comment comment,,,,,,,setup - load module and init with a capturing logger -before,0,0,q,handlers:use`di.handlers,1,1,load di.handlers module +before,0,0,q,handlers:use`di.torq.handlers,1,1,load di.torq.handlers module before,0,0,q,.hh.captbl:([]lvl:`symbol$();ctx:`symbol$();msg:()),1,1,log capture table for assertions before,0,0,q,caplog:`info`warn`error!({[c;m] `.hh.captbl insert (`info;c;m)};{[c;m] `.hh.captbl insert (`warn;c;m)};{[c;m] `.hh.captbl insert (`error;c;m)}),1,1,capturing binary logger {[c;m]} before,0,0,q,handlers.init[enlist[`log]!enlist caplog],1,1,init with the capturing logger @@ -12,7 +12,7 @@ fail,0,0,q,handlers.init[()!()],1,1,init rejects missing log key fail,0,0,q,handlers.init[enlist[`log]!enlist 42],1,1,init rejects a non-dict log value fail,0,0,q,handlers.init[enlist[`log]!enlist `info`warn!(caplog`info;caplog`warn)],1,1,init rejects a log dict missing the error key run,0,0,q,.hh.errstr:@[{handlers.init[()!()]};(::);{x}],1,1,capture the error string from a bad init -true,0,0,q,.hh.errstr like "di.handlers:*",1,1,init error is prefixed di.handlers: +true,0,0,q,.hh.errstr like "di.torq.handlers:*",1,1,init error is prefixed di.torq.handlers: comment,,,,,,,module metadata - exported version true,0,0,q,10h=type handlers.version,1,1,version is a string @@ -152,9 +152,10 @@ true,0,0,q,not {x}~value `.z.ws,1,1,the exec install binds a dispatcher not the run,0,0,q,handlers.register[`.z.ws;`post;`w1;0;{[r;a]}],1,1,attach a post handler run,0,0,q,handlers.remove[`.z.ws;`exec;`o1],1,1,remove the owner true,0,0,q,0=count handlers.list[`.z.ws],1,1,list is empty after owner removal -true,0,0,q,not `.z.ws in key .m.di.0handlers.ownerfunc,1,1,the owner function entry is cleared -true,0,0,q,not `.z.ws in key .m.di.0handlers.pre,1,1,the pre table entry is cleared -true,0,0,q,not `.z.ws in key .m.di.0handlers.post,1,1,the post table entry is cleared +true,0,0,q,not `.z.ws in key .m.di.0torq.0handlers.ownerfunc,1,1,the owner function entry is cleared +true,0,0,q,not `.z.ws in key .m.di.0torq.0handlers.pre,1,1,the pre table entry is cleared +true,0,0,q,not `.z.ws in key .m.di.0torq.0handlers.transform,1,1,the transform table entry is cleared +true,0,0,q,not `.z.ws in key .m.di.0torq.0handlers.post,1,1,the post table entry is cleared run,0,0,q,handlers.register[`.z.ws;`exec;`o2;0;{2*x}],1,1,register a fresh owner on the same event true,0,0,q,6~(value `.z.ws) 3,1,1,the fresh owner is in effect through a new dispatcher @@ -175,10 +176,10 @@ run,0,0,q,.hh.captbl:0#.hh.captbl,1,1,reset log capture run,0,0,q,.hh.trap:@[{handlers.register[`.z.zz;`;`x;0;{x}]};(::);{x}],1,1,trap a rejected registration true,0,0,q,any `error = exec lvl from .hh.captbl,1,1,the domain error was logged at error -comment,,,,,,,the signalled string is the house idiom - di.handlers-prefixed with no per-function context tag and equal to the logged message +comment,,,,,,,the signalled string is the house idiom - di.torq.handlers-prefixed with no per-function context tag and equal to the logged message run,0,0,q,.hh.captbl:0#.hh.captbl,1,1,reset log capture run,0,0,q,.hh.sig:@[{handlers.register[42;`;`x;0;{x}]};(::);{x}],1,1,capture the signal from a representative rejected register -true,0,0,q,.hh.sig like "di.handlers: event must be a symbol",1,1,signal is di.handlers-prefixed with no register: context tag +true,0,0,q,.hh.sig like "di.torq.handlers: event must be a symbol",1,1,signal is di.torq.handlers-prefixed with no register: context tag true,0,0,q,.hh.sig~last exec msg from .hh.captbl where lvl=`error,1,1,the signalled string equals the logged error message true,0,0,q,`register=last exec ctx from .hh.captbl where lvl=`error,1,1,the per-function context is on the log symbol arg not in the signal @@ -193,3 +194,24 @@ run,0,0,q,handlers.remove[`.z.pi;`exec;`owner],1,1,restore default .z.pi run,0,0,q,handlers.remove[`.z.pp;`exec;`o],1,1,restore default .z.pp run,0,0,q,handlers.remove[`.z.pw;`exec;`auth],1,1,restore default .z.pw run,0,0,q,handlers.remove[`.z.ws;`exec;`o2],1,1,restore default .z.ws + +comment,,,,,,,phased transform (TorqX addition) - transforms rewrite the result in priority order between exec and post +fail,0,0,q,handlers.register[`.z.ps;`transform;`x;0;{x}],1,1,transform before an exec owner is rejected like pre and post +run,0,0,q,handlers.register[`.z.pg;`exec;`o;0;{x}],1,1,identity exec owner on a freshly-cleaned event +run,0,0,q,handlers.register[`.z.pg;`transform;`plus1;10;{x+1}],1,1,transform plus1 at priority 10 +run,0,0,q,handlers.register[`.z.pg;`transform;`times10;20;{10*x}],1,1,transform times10 at priority 20 +run,0,0,q,handlers.register[`.z.pg;`post;`obs;0;{[r;a] .tt.pr::r}],1,1,post captures the result it observes +run,0,0,q,.tt.res:(value `.z.pg) 5,1,1,drive the dispatcher with request 5 +true,0,0,q,.tt.res~60,1,1,exec identity 5 then transform plus1 to 6 then times10 to 60 in priority order +true,0,0,q,.tt.pr~60,1,1,post observes the transformed result 60 not the raw exec result 5 +true,0,0,q,(exec phase from handlers.list[`.z.pg])~`exec`transform`transform`post,1,1,list shows transforms between the exec owner and post in dispatch order +run,0,0,q,handlers.register[`.z.pg;`transform;`plus1;10;{x+100}],1,1,re-register the same transform name replaces its body in place +run,0,0,q,.tt.res2:(value `.z.pg) 5,1,1,drive again after the transform reclaim +true,0,0,q,.tt.res2~1050,1,1,plus1 body replaced (5 to 105) then times10 to 1050 - replaced not duplicated +true,0,0,q,2=count select from handlers.list[`.z.pg] where phase=`transform,1,1,duplicate transform name did not grow the table +run,0,0,q,handlers.remove[`.z.pg;`transform;`times10],1,1,remove one transform handler leaving plus1 +run,0,0,q,.tt.res3:(value `.z.pg) 5,1,1,drive after removing times10 +true,0,0,q,.tt.res3~105,1,1,only plus1 remains so 5 becomes 105 +run,0,0,q,handlers.remove[`.z.pg;`exec;`o],1,1,remove the exec owner clears all phased state including transform +true,0,0,q,0=count handlers.list[`.z.pg],1,1,list empty after owner removal +true,0,0,q,not `.z.pg in key .m.di.0torq.0handlers.transform,1,1,the transform table entry is cleared on owner removal diff --git a/di/handlers/test_integration.csv b/di/torq/handlers/test_integration.csv similarity index 93% rename from di/handlers/test_integration.csv rename to di/torq/handlers/test_integration.csv index 7be75519..5917010f 100644 --- a/di/handlers/test_integration.csv +++ b/di/torq/handlers/test_integration.csv @@ -5,11 +5,11 @@ comment,,,,,,,the child port is OS-assigned via \p 0W - no env var no hardcoded comment,,,,,,,cleanup is robust to mid-suite failure - the child self-exits when the parent connection drops for any reason comment,,,,,,,note k4unit runs every before row first then the asserts - so results are captured in befores and checked in trues -before,0,0,q,handlers:use`di.handlers,1,1,load di.handlers module +before,0,0,q,handlers:use`di.torq.handlers,1,1,load di.torq.handlers module before,0,0,q,logdep:`info`warn`error!({[c;m]};{[c;m]};{[c;m]}),1,1,silent no-op log mock before,0,0,q,handlers.init[enlist[`log]!enlist logdep],1,1,init the module before,0,0,q,.hh.iev:([]who:`symbol$()),1,1,capture table for observer firings -before,0,0,q,handlers.register[`.z.pc;`;`itest;0;{[w] `.hh.iev insert `closed}],1,1,register a real .z.pc observer through di.handlers +before,0,0,q,handlers.register[`.z.pc;`;`itest;0;{[w] `.hh.iev insert `closed}],1,1,register a real .z.pc observer through di.torq.handlers before,0,0,q,qcands:$[count qh:getenv[`QHOME];(raze(qh;"/bin/q");raze(qh;"/";string .z.o;"/q"));()],1,1,candidate q binary locations for kdbx and classic layouts before,0,0,q,qbin:$[count ex:qcands where {not ()~key hsym `$x} each qcands;first ex;"q"],1,1,pick the first candidate that exists else fall back to q on PATH before,0,0,q,.it.tryopen:{[p] @[{hopen (`$"" sv (":localhost:";string x);500)};p;0Ni]},1,1,attempt one connection returning a null handle on failure @@ -27,7 +27,7 @@ before,0,0,q,@[{system "" sv ("kill -9 ";string cpid)};::;{x}],1,1,forceful kill before,0,0,q,system"sleep 0.3",1,1,give the OS a moment to reap the child before,0,0,q,.it.gone:0=count @[{system "" sv ("ps -p ";string cpid;" -o pid=")};::;{()}],1,1,verify the child process is actually gone (ps errors when absent so the probe is protected) -comment,,,,,,,a real IPC round-trip works while di.handlers is loaded +comment,,,,,,,a real IPC round-trip works while di.torq.handlers is loaded true,0,0,q,.it.roundtrip,1,1,synchronous query to the real child process returned the expected result comment,,,,,,,closing the real connection drives the registered .z.pc observer diff --git a/di/torq/init.q b/di/torq/init.q new file mode 100644 index 00000000..44c937ee --- /dev/null +++ b/di/torq/init.q @@ -0,0 +1,5 @@ +\l ::torq.q + +version:first read0`:::VERSION + +export:([init;version]) diff --git a/di/torq/logroll/VERSION b/di/torq/logroll/VERSION new file mode 100644 index 00000000..0ea3a944 --- /dev/null +++ b/di/torq/logroll/VERSION @@ -0,0 +1 @@ +0.2.0 diff --git a/di/torq/logroll/init.q b/di/torq/logroll/init.q new file mode 100644 index 00000000..8ef4e725 --- /dev/null +++ b/di/torq/logroll/init.q @@ -0,0 +1,5 @@ +\l ::logroll.q + +version:first read0`:::VERSION + +export:([resolvedir;redirect;rollnow;interactive;init;version]) diff --git a/di/torq/logroll/logroll.md b/di/torq/logroll/logroll.md new file mode 100644 index 00000000..cc9c2daa --- /dev/null +++ b/di/torq/logroll/logroll.md @@ -0,0 +1,172 @@ +# di.torq.logroll + +Optional stdout/stderr redirection and daily rotation, ported from `TorQ/torq.q`'s +`fileredirect`/`createalias`/`createlog`/`rolllogauto` (`torq.q:458-500,656-661`). +TorQ made this mandatory-by-default; TorqX makes it **opt-in**, since an app that +ships its output to Logstash/ELK wants everything on stdout/journal untouched, and +would lose that if this were forced on. Named to match `torq.q`'s own +`.proc.logroll` flag. + +## Design + +A process opts in with a `[logroll]` settings section: + +```toml +[logroll] +enabled = true +dir = "logs" # relative to TORQXAPPHOME, or absolute +suppressalias = false # true skips the out_.log/err_.log symlinks +forceredirect = false # true redirects even in an interactive session (see TTY guard below) +``` + +A missing `[logroll]` section, or `enabled` absent/false, is a **silent no-op** - +same convention as `di.torq.depcheck.check` on a missing `deps.toml`. `di.torq.init` +calls `di.torq.logroll.init[config;deps]` unconditionally on every process start (right +after the injected `deps` dict is built, *before* the process type's own +`init`/`run` - so the process type's own startup log lines land in the rolled files +too), so a process gets this purely by adding the section to its settings - no +per-process-type code changes needed anywhere. + +### `resolvedir[dir]` + +String-based (not symbol/`hsym`, since this feeds `system"1 ..."`/`ln -sf` shell +commands, not a q file load) - `di/proc/hdb/hdb.q`'s `resolvedir` is the symbol-based +equivalent for mounting a database directory. Absolute if the (string-normalized) +value starts with `/`, else joined against `TORQXAPPHOME`. A symbol-sourced value +(old `.q`-style settings, e.g. `` `:/var/log/myapp ``) stringifies with its leading +handle colon still attached - stripped before the absolute-ness check. + +### `redirect[dir;filename;alias;handle]` / `rollnow[]` + +`redirect` reassigns fd 1 or 2 (`handle`) to a real file via `system"1 ..."`/ +`system"2 ..."` - kdb+'s own console-handle redirection, a real OS-level fd +reassignment - and, if `alias` is non-empty, points a stable `ln -sf` symlink at it. +`rollnow` builds this roll's timestamp-stamped `out_`/`err_` filenames and calls +`redirect` for both handles. Published at a real root name, `.logroll.rollnow`, so +it's callable manually (ops forcing an immediate roll without waiting for the +schedule) - same "publish at a real root name" convention `di.proc.hdb`'s +`.hdb.reload` uses, needed because `use` mangles a module's own namespace. + +### Interactive sessions (the TTY guard) + +Redirecting the console is right for a **background/daemon** process, but wrong when the process +is launched **interactively** - by hand via the `torqx` alias, or inside a tmux pane. Redirecting +stdout/stderr there steals the operator's console: the startup banner prints (before `init` runs), +then the `q)` prompt and everything after vanish into the logfile, so the process *looks* hung even +though it is perfectly healthy and answering IPC. + +So `init` first checks `interactive[]` - is q's stdin a TTY? `interactive` shells out +(`test -t 0`) via `system`, whose child inherits q's own fd 0, so it reflects q's real stdin: a +`nohup` launch (stdin `/dev/null`), a systemd unit, or a stdin-detached child are all **not** a +TTY and redirect as normal; an operator at a terminal or a tmux pane **is** a TTY, and `init` +**skips** the redirect (and the roll schedule) with a one-line warning, leaving the console intact. +The probe is error-guarded: if it fails for any reason, it assumes *not* interactive (redirect - +the safe default for a real deployment). Set `[logroll] forceredirect = true` to redirect even in +an interactive session. + +> This also matters for `torqx.sh`'s tmux dev mode (`start --tmux` / `devstart`): a tmux pane is a +> TTY, so a logroll-enabled process keeps a usable console when you `torqx.sh attach` to it, while +> `torqx.sh`'s own `pipe-pane` still tees that pane to a logfile. Without the guard, attaching to a +> logroll-enabled process would show a dead console. +> +> Historical note: because kdb+'s `\1`/`\2` split stdout/stderr correctly only on a non-TTY stdin +> in this build, an interactively-launched logroll process used to also merge all output into the +> `err_` file (`out_` left empty). The TTY guard removes that as a side effect - interactive +> sessions no longer redirect at all, and background launches split `out_`/`err_` correctly. + +### `init[config;deps]` + +Requires `log` and `timer` in the injected `deps` (same validation style as +`di/proc/hdb/hdb.q:21`). When enabled: calls `rollnow[]` once immediately, then +schedules the recurring roll via the injected timer contract - `period=86400` +(seconds/day), `mode=1h` (`kdbx-modules` `di.timer`'s "x seconds after previously +scheduled start" - fixed-rate, no drift), with `opts.startattime` overriding just +the first fire to next UTC midnight (`` `timestamp$1+`date$.z.p ``), so the very +first roll happens at the next real day boundary rather than 24h after whenever the +process happened to start - matching `torq.q`'s own scheduling exactly. The timer +job is handed the actual `rollnow` **function value**, not a symbol reference - a +bare `` `.di.torq.logroll.rollnow `` symbol would not reliably resolve later given how +`use` mangles a module's namespace, but the closure captured at `init`-time always +will (same `.z.m`-resolves-to-origin-module guarantee `.hdb.reload` relies on). + +v1 scope matches `torq.q`'s existing behavior exactly rather than adding new knobs: +always UTC midnight (no `-localtime`-equivalent config), always a 1-day period (no +configurable roll hour/interval), unix `ln -sf` only (no Windows `mklink` branch - +TorqX is Linux-only so far). All flagged as known gaps below, not built, since the +ask was to retain existing TorQ behavior, not extend it. + +## The systemd interaction + +`torqx.sh`'s own `${TORQXLOGDIR:-/tmp}` default is bash-level redirection used only +by the non-systemd `start_one` path (`> "$logfile" 2>&1 &`) - it captures fd 1/2 +until something else reassigns them. A generated `export-systemd` unit has no such +redirect at all; stdout/stderr go to the journal by default. + +`di.torq.logroll`'s redirect **takes over from whichever supervisor initially owned fd +1/2, identically regardless of launch mode** - it's a real fd reassignment, not +something layered on top. Enabling `di.torq.logroll` under a systemd unit makes +`journalctl` go quiet for that unit the moment the redirect fires (the same +startup-banner-only transient you'd see under the old `/tmp` capture); the flat +files under `di.torq.logroll`'s configured `dir` become the sole source of truth from +then on. Confirmed directly, not just asserted: running `hdb` via `torqx.sh start +hdb` with `[logroll]` enabled left the original `torqx.sh` nohup-redirect target +file (`/tmp/torqx__hdb.log`) completely empty, while the configured `dir` +picked up every line, including `hdb`'s own mounting/loaded messages and the +launcher's `torqx: started hdb hdb` line. No change to `torqx.sh`/`export-systemd` +is needed to support this - the generated unit's `ExecStart` is untouched either +way, and `WorkingDirectory`/`TORQXAPPHOME` already being absolute means +`resolvedir` has no cwd dependency to worry about under systemd. + +## Dependency + +Requires `log` and `timer` injected (Tier-2-ish, alongside `di.proc.hdb`/`di.torq.handlers`) - not +a hard `use`-imported module dependency beyond that. + +## Usage + +```q +q)lr:use`di.torq.logroll +q)(lr`init)[config;deps] / no-op unless config has [logroll] enabled=true +q).logroll.rollnow[] / force an immediate re-roll, e.g. from a qcon session +``` + +In practice nothing calls these directly - `di.torq.init` calls `init` on every +process start: + +```q +lr:use`di.torq.logroll; +(lr`init)[config;deps]; +``` + +## Known gaps (v1) + +- Always UTC midnight, always a 1-day period - no `-localtime`-equivalent config, + no configurable roll hour/interval. Matches `torq.q`'s existing behavior exactly; + extending this means adding settings keys and threading them into the + `addjob`/`startattime` calculation in `init`, not a design change. +- Unix `ln -sf` only - no Windows `mklink` branch (`torq.q`'s `createalias` has + one). Add if TorqX ever needs to run on Windows. +- No log-file cleanup/retention policy - old `out_`/`err_` files accumulate + forever under `dir`, same as `torq.q`'s own behavior (which also never deletes + old files). External housekeeping (e.g. a cron job) is expected, same as today. + +## Testing + +`test.csv`/`test.q` (k4unit) cover the no-op paths (missing `[logroll]` section, +`enabled=false`) and the missing-`log`/missing-`timer` dependency failures +in-process (safe - these all return/throw before ever touching fd 1/2). The +"enabled" cases - real redirect, aliasing, `suppressalias`, relative-dir +resolution, and the exact `addjob` call shape - are each run via +`test_childinit.q`, spawned as a genuine separate q process +(`spawnchildinit` in `test.q`), **not** called in-process: confirmed empirically +that calling `logroll.init` with `enabled=true` directly inside the k4unit test +runner reassigns the runner's own fd 1/2 and corrupts its own result reporting +(same class of problem `di/torq/servers/test.q` solves by spawning a real peer process +for its own self-connect case). The spawned child serializes its captured +`addjobcalls` mock-table to disk before exiting so the parent process can load and +assert on it. Run with: + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.torq.logroll +``` diff --git a/di/torq/logroll/logroll.q b/di/torq/logroll/logroll.q new file mode 100644 index 00000000..04cf3950 --- /dev/null +++ b/di/torq/logroll/logroll.q @@ -0,0 +1,97 @@ +/ di.torq.logroll - optional stdout/stderr redirection + daily rotation, ported from +/ TorQ/torq.q's fileredirect/createalias/createlog/rolllogauto (torq.q:458-500, +/ 656-661). Off by default - a process opts in via a [logroll] settings section; +/ absent/disabled is a silent no-op, same convention as di.torq.depcheck on a missing +/ deps.toml. See logroll.md for the systemd interaction - the redirect below takes +/ over from whatever supervisor (bash nohup capture, or systemd's journal) +/ initially owned fd 1/2, regardless of launch mode. + +/ detect an interactive session: is q's stdin a TTY? A background/daemon launch (nohup -> +/ /dev/null, systemd, or a spawned child with stdin detached) is NOT a tty; an operator running +/ the process by hand (the `torqx` alias) or a tmux pane IS. Redirecting the console away from an +/ interactive operator makes the process look hung (banner, then no q) prompt, no visible input - +/ everything goes to the logfile) even though it is perfectly healthy, so logroll skips the +/ redirect in that case (see init). The probe's child inherits q's own fd 0, so `test -t 0` +/ reflects q's real stdin. Error-guarded: if the probe fails for any reason, assume NOT interactive +/ (redirect - the safe default for a real deployment). +/ NB the probe MUST go through an explicit `sh -c "..."`: this kdb-x build's `system` execs the +/ command DIRECTLY (no implicit /bin/sh), so a bare `test -t 0 && echo ...` would exec `test` with +/ the `&&`/`echo` as junk args - `test` never writes to stdout (it only sets an exit code), so the +/ call returns empty and the tty is never detected (this was a real bug: the guard always fell +/ through to "notty" and redirected even interactively). `sh -c` runs a real shell that evaluates +/ the `&&`/`||` and echoes tty|notty. +interactive:{"tty"~@[{first system"sh -c \"test -t 0 && echo tty || echo notty\""};();{"notty"}]} + +/ resolves a dir setting to a plain string path - absolute if it starts with "/", +/ else joined against TORQXAPPHOME. String-based (not symbol/hsym), since this +/ feeds `system"1 ..."`/`ln -sf` shell commands, not a q file load - di/proc/hdb/hdb.q's +/ resolvedir is the symbol-based equivalent for mounting a database directory. +resolvedir:{[dir] + dir:$[10h=abs type dir;dir;string dir]; + / a symbol-sourced value (old .q-style settings) stringifies with its leading + / handle colon still attached (e.g. `:/tmp/foo` -> ":/tmp/foo") - strip it before + / checking absolute-ness, same normalization di.proc.hdb's resolvedir needs (1_string). + dir:$[(0 -resultdir +/ Assumes cwd is the TorqX repo root (same assumption test.q itself documents). + +args:.Q.opt .z.x; +cfgname:first args`cfg; +resultdir:first args`resultdir; + +system "l di/torq/logroll/test.q"; +logroll:use`di.torq.logroll; + +cfg:(value cfgname)[]; +logroll.init[cfg;mockdeps[]]; + +/ addjobcalls only exists in this throwaway process's memory - serialize it so the +/ parent test process can load and assert on it after this process exits. +(hsym `$resultdir,"/addjobcalls_result") set addjobcalls; + +exit 0 diff --git a/di/torq/servers/VERSION b/di/torq/servers/VERSION new file mode 100644 index 00000000..9325c3cc --- /dev/null +++ b/di/torq/servers/VERSION @@ -0,0 +1 @@ +0.3.0 \ No newline at end of file diff --git a/di/torq/servers/init.q b/di/torq/servers/init.q new file mode 100644 index 00000000..97ceb222 --- /dev/null +++ b/di/torq/servers/init.q @@ -0,0 +1,3 @@ +/ connection management and handle-by-type lookup for the modular torq world. +\l ::servers.q +export:([init;startup;getservers;gethandlebytype;waitfortype;getapimeta]) diff --git a/di/torq/servers/servers.md b/di/torq/servers/servers.md new file mode 100644 index 00000000..3cbc748c --- /dev/null +++ b/di/torq/servers/servers.md @@ -0,0 +1,130 @@ +# di.torq.servers + +Connection management and handle-by-type lookup for the modular TorQ world — the `di.*` +analogue of TorQ's `.servers` (`code/handlers/trackservers.q` + `servers.q`), scoped down +for v1: no discovery service, no password/access-list files, no non-TorQ process tracking, +no FinSpace. `process.csv` here is a static **phone book** (who to *dial*), **not** an +identity source — self-identity comes from config, injected by `di.torq`. + +FRAMEWORK-tier module: no hard `di.*` dependencies; `log`, `timer` and `handlers` are all +**injected** (all required, no fallback). + +## init and config + +Standard **one-arg `init[deps]`**: `di.torq` merges this process's resolved config slice into +the same `deps` dict it passes the injectables in, so `deps` carries both the injectable +dependencies **and** the config keys. `init` wires the deps, records self-identity, and +installs two one-time process-global side effects — a `.z.pc` cleanup handler and a 10s retry +timer job. It is **idempotent** (guarded by an internal `registered` flag): `di.torq` calls +it once per process, but a second call refreshes the dep refs without re-registering (a +duplicate `di.timer.addjob` id would throw). `init` does **not** open connections. + +`deps` keys: + +| key | kind | meaning | +|---|---|---| +| `log` | injectable | binary `` `info`warn`error `` `{[c;m]}` logger dict | +| `timer` | injectable | di.timer contract; `addjob` = the 6-arg `custom` form `{[id;func;params;period;mode;opts]}` | +| `handlers` | injectable | di.torq.handlers contract; `register[event;phase;nm;pri;func]` | +| `proctype`/`procname` | config | this process's own identity (required); used to exclude self from `process.csv` | +| `connections` | config | proctypes this process should dial (symbols, or strings from a `.toml` cascade — normalised). Optional; default = none | +| `processcsv` | config | **path** to `process.csv`; supplied by di.torq. Optional; required only once `connections` is non-empty | + +```q +svc:use`di.torq.servers +svc.init[deps] / deps = injectables + config, assembled by di.torq +svc.startup[] / open the configured connections (reads init config) +h:svc.gethandlebytype[`hdb;`any] +h "1+1" +``` + +## Exported functions + +| Function | Signature | Description | +|---|---|---| +| `init` | `init[deps]` | Wire deps + config, record identity, install the `.z.pc` handler + retry job. Idempotent. | +| `startup` | `startup[]` | Read `process.csv` (`processcsv`), drop self, connect to each row whose proctype is in `connections`. A failed connection is logged (not raised) and left as `w:0Ni` for `retry`. No-op if no connections configured. | +| `getservers` | `getservers[proctype]` | Live (`w` non-null) `SERVERS` rows for a proctype. | +| `gethandlebytype` | `gethandlebytype[proctype;selection]` | One live handle via `` `any``/`roundrobin`/`last``; `0Ni` if none. Bumps usage stats. | +| `waitfortype` | `waitfortype[proctype;timeoutms;pollms]` | Block until a live connection exists or timeout; `1b`/`0b`. Caller decides if a timeout is fatal. `startup` must have run first. | +| `getapimeta` | `getapimeta[]` | This module's api metadata, one row per **callable** API function (`init`/`getapimeta` plumbing omitted), for `di.torq` to register with `di.api`. | + +Export is deliberately conservative — only functions `di.torq` or a consumer actually calls +(so `di.api` lists exactly these). The rest are **internal**: `retry` (the scheduled +`serversretry` job — passed to the timer *by value* at init, so it needs no export; it first +runs `cleanup` to sweep ungracefully-vanished handles, then reopens every dead handle), +`cleanup`, `formathp`, `opencon`, `readprocesscsv`, `retryrows`, `selector`, `updatestats`, +`signalfound`, `raiseerror`; plus state (`SERVERS`, `self`, `registered`, `HOPENTIMEOUT`, +`connections`, `processcsv`). + +## The `SERVERS` table + +```q +SERVERS:([]procname:`symbol$();proctype:`symbol$();hpup:`symbol$();w:`int$();hits:`int$();startp:`timestamp$();lastp:`timestamp$();endp:`timestamp$()) +``` + +A direct analogue of legacy TorQ's `.servers.SERVERS`: `w` is the live handle (`0Ni` when +disconnected), `hits`/`lastp` drive handle selection, `startp`/`endp` track lifecycle. + +## `.z.pc` registration via di.torq.handlers + +`.z.pc` (connection closed) is a **simple/observer** event in di.torq.handlers — side-effect only, +fan-out — so di.torq.servers registers its cleanup callback through the injected `handlers` +dependency rather than assigning `.z.pc` directly: + +```q +(handlers[`register])[`.z.pc;`;`servers;0j;pcfunc] +``` + +`register`'s signature is `register[event;phase;nm;pri;func]`; for a simple event the `phase` +must be `` ` `` (null) — di.torq.handlers rejects a non-null phase on an observer event. This lets +di.torq.servers' disconnect hook coexist with every other `.z.pc` registrant in the same +priority-ordered fan-out. + +## Conventions (learnings from di.torq.config) + +- **One-arg `init[deps]`** with config folded into `deps` (the project convention; matches + `di.eodtime`'s optional-config-in-deps pattern), not a two-arg `init[config;deps]`. +- **Three-flat-var logging** — `.z.m.loginfo`/`.z.m.logwarn`/`.z.m.logerr`, matching + `consistency.md`, `di.compression` and `di.torq.config`. (The project hasn't globally frozen this + vs. the single-dict form — flag before changing.) +- **`raiseerror` (log-then-signal)** for all post-init domain errors (`formathp` unknown + ipctype, `selector` unknown selection, missing `process.csv`). `init`'s own dependency + validation is the one exception (plain `'` — no logger yet). +- **`getapimeta`** exported; a test asserts it documents exactly the module's *callable* + exports — `init`/`getapimeta` are plumbing (di.torq calls them by convention) and are + deliberately omitted from the registry rows, matching di.util.toml and the skill convention. No + `version` export / VERSION file yet — deferred to the di.torq.depcheck rollout, as in di.torq.config. +- **Env-free** — di.torq.servers reads no environment variable; the `process.csv` path arrives via + `config`processcsv` (di.torq resolves it), holding di.torq.config's env-free boundary. + +## Open items / not yet done + +- **Live-peer integration tests are in place** (`test.q` + `test.csv`, 33 checks). They spawn a + genuinely separate `q` peer (a self-connect returns pseudo-handle `0`, not a real socket) and + cover: `startup` connecting to a live peer and logging a failed dial while excluding self, + `gethandlebytype` returning a live remote handle (`2=h"1+1"`), the retry cycle recovering an + ungraceful kill (`cleanup`+reopen), and `waitfortype` connected-vs-timeout — plus the mockable + surface (init validation, dep-wiring, idempotency, input validation, `getapimeta`). Because + `retry`/`cleanup` are internal, the retry cycle is driven by invoking the callback the **mock + timer captured** at `addjob` (the actually-wired path), not a direct export. +- **Injected providers are mocked in tests by design.** `di.util.log` and `di.torq.handlers` are + both present on this branch now (log = the real structured logger from `main` PR #90), but the + unit tests still mock them so a failure localises to `di.torq.servers` rather than a provider. + The handlers mock uses the real `register[event;phase;nm;pri;func]` shape from `handlers.q`; the + real wiring is exercised end-to-end by di.torq's own suite. +- **`config`processcsv` and the assembled `connections` list** depend on di.torq's config + wiring — coordinate when di.torq's servers dep is built. +- Scoped-out (v1): discovery service, password/access-list files, non-TorQ tracking, and the + `tcps`/`unix` socket types end-to-end (only `tcp` is wired through `startup`). + +## Tests + +Run in a fresh q session (spawns and kills a real peer process; don't interleave with other +modules' tests). Needs `QHOME` set (the peer is launched via `$QHOME/bin/q`) and `di.os` on +`QPATH` (the harness uses `os.abspath` to load `test.q`): + +```q +k4unit:use`di.k4unit +k4unit.moduletest`di.torq.servers +``` diff --git a/di/torq/servers/servers.q b/di/torq/servers/servers.q new file mode 100644 index 00000000..5d7dcb21 --- /dev/null +++ b/di/torq/servers/servers.q @@ -0,0 +1,241 @@ +/ connection management and handle-by-type lookup for the modular torq world - the di.* analogue +/ of TorQ's .servers (code/handlers/trackservers.q + servers.q), scoped down for v1: no discovery +/ service, no password/access-list files, no non-torq process tracking, no FinSpace. process.csv +/ is a static phone book (who to dial), NOT an identity source - self-identity comes from config. +/ FRAMEWORK-tier module: no hard di.* deps; log, timer and handlers are injected (all required). +/ standard one-arg init[deps]: di.torq merges this process's config slice (proctype/procname, +/ connections, processcsv) into the same deps dict it passes the injectables in. conventions match +/ di.torq.config: strict init validation (no fallback), three-flat-var logging, log-then-signal via +/ raiseerror, getapimeta for di.api, and the env-free boundary (the process.csv path arrives via +/ config; di.torq.servers reads no env itself). + +/ --- module-local state (initial values at load; read/written via .z.m at runtime) --- + +SERVERS:([] + procname:`symbol$(); + proctype:`symbol$(); + hpup:`symbol$(); + w:`int$(); + hits:`int$(); + startp:`timestamp$(); + lastp:`timestamp$(); + endp:`timestamp$()); + +HOPENTIMEOUT:2000; + +self:`proctype`procname!``; + +/ guards init's one-time process-global side effects (the .z.pc observer + the retry timer job) so +/ init is IDEMPOTENT - di.torq calls it once per process, but a second call (a test re-run, a +/ future re-init) must not re-register: di.timer.addjob throws on a duplicate id. the dep refs are +/ always refreshed; only the one-time registrations are guarded. +registered:0b; + +raiseerror:{[ctx;msg] + / internal - log an error under ctx via the injected logger, then signal it, so a failure is + / observable in the log as well as thrown. used for all post-init domain errors (init's own + / dependency validation signals with a plain ' - the logger is not wired yet). + .z.m.logerr[ctx;msg]; + '"di.torq.servers: ",string[ctx],": ",msg; + }; + +init:{[deps] + / wire the injected deps (log/timer/handlers - all required, no fallback) and this process's + / config (proctype/procname identity, connections, processcsv), and install the one-time side + / effects (a .z.pc cleanup observer via handlers + a 10s serversretry job via timer). config + / arrives in the SAME deps dict (the one-arg init convention - di.torq merges the config slice + / into it). idempotent (see `registered). does NOT open connections - that is startup's job. + if[99h<>type deps; + '"di.torq.servers: deps must be a dict of injectables + config"]; + if[not all `log`timer`handlers in key deps; + '"di.torq.servers: log, timer and handlers dependencies are required (see di.util.log, di.timer, di.torq.handlers)"]; + if[99h<>type deps`log; + '"di.torq.servers: log value must be a dict; pass `info`warn`error functions"]; + if[not all (`info`warn`error) in key deps`log; + '"di.torq.servers: log dict must have `info`warn`error keys; got: ",(", " sv string key deps`log)]; + if[99h<>type deps`timer; + '"di.torq.servers: timer value must be a dict (see di.timer)"]; + if[99h<>type deps`handlers; + '"di.torq.servers: handlers value must be a dict (see di.torq.handlers)"]; + if[not all `proctype`procname in key deps; + '"di.torq.servers: proctype and procname (self-identity) are required in deps"]; + if[not all -11h=type each deps`proctype`procname; + '"di.torq.servers: proctype and procname must be symbols"]; + .z.m.loginfo:deps[`log]`info; + .z.m.logwarn:deps[`log]`warn; + .z.m.logerr:deps[`log]`error; + .z.m.timer:deps`timer; + .z.m.handlers:deps`handlers; + .z.m.self:`proctype`procname!deps`proctype`procname; + .z.m.connections:$[`connections in key deps;deps`connections;`symbol$()]; + .z.m.processcsv:$[`processcsv in key deps;deps`processcsv;""]; + if[not .z.m.registered; + / .z.pc is a SIMPLE (observer) event in di.torq.handlers - side-effect only, fan-out. registered via + / the injected handlers dep with di.torq.handlers' register[event;phase;nm;pri;func] contract; phase + / is ` (null) for a simple event, pri 0. the callback marks a closed handle's row disconnected. + / (param `wh`, not `w`, so it does not shadow the SERVERS column w.) + pcfunc:{[wh] .z.m.SERVERS:update endp:.z.p,w:0Ni from .z.m.SERVERS where w=wh; }; + (.z.m.handlers[`register])[`.z.pc;`;`servers;0j;pcfunc]; + / di.timer mode-1h period is in SECONDS, so 10 = a 10-second retry (a bare 10000 here would be + / ~2.8h - the latent typo that made dead-handle recovery effectively never fire in early POCs). + (.z.m.timer[`addjob])[`serversretry;retry;();10;1;()!()]; + .z.m.registered:1b; + ]; + .z.m.loginfo[`init;"di.torq.servers initialised"]; + }; + +formathp:{[host;port;ipctype] + / internal - build a connection-handle symbol for `tcp`/`tcps`/`unix. only `tcp is exercised by + / startup in v1; the others exist for a future SOCKETTYPE-style config. + h:string host; + p:string port; + $[ipctype=`tcp; lower `$":",h,":",p; + ipctype=`tcps;lower `$":tcps://",h,":",p; + ipctype=`unix;lower `$":unix://",p; + raiseerror[`formathp;"unknown ipctype ",string ipctype]] + }; + +opencon:{[hpup] + / open a connection, logging (not erroring) on failure - a downed peer isn't necessarily an + / error at connect time; retry keeps trying. NOTE the timeout form is hopen[(handle;timeoutms)] + / (a single 2-item list), not the dyadic hopen[handle;timeoutms], which throws 'rank. + r:@[{(hopen (x;.z.m.HOPENTIMEOUT);"")};hpup;{(0Ni;x)}]; + if[null first r;.z.m.logwarn[`servers;"failed to open connection to ",(string hpup),": ",last r]]; + first r + }; + +readprocesscsv:{[path] + / internal - read the static process.csv phone book (host,port,proctype,procname). the PATH is + / supplied by the caller (from config`processcsv); di.torq.servers reads no env itself, holding + / di.torq.config's env-free boundary - di.torq resolves the path and puts it in config. + fsym:`$":",path; + if[0=count key fsym;raiseerror[`readprocesscsv;"process.csv not found at ",path]]; + ("SISS";enlist",") 0: fsym + }; + +startup:{[config] + / open connections to every process.csv row whose proctype is in the configured connections list, + / excluding this process's own row. `connections` and `processcsv` are read from the config arg - + / NOT from init - because each consumer computes its OWN role-specific connection list (e.g. an rdb + / dials its tickerplant+hdb types, a gateway its backend types) and passes it in via its config + / slice; di.torq cannot know that list at init time. a failed connection is logged (not raised) and + / left as w:0Ni for retry. a no-op if no connections are configured. + / normalise connections to symbols to match process.csv's `proctype column (always a symbol via + / the "S" spec): a .q settings file gives symbols already (`$ throws 'type on a symbol - it is + / NOT idempotent, hence the type check); a .toml one gives plain strings (TOML has no symbol). + conns:$[`connections in key config;config`connections;`symbol$()]; + conns:$[11h=abs type conns;conns;`$conns]; + if[0=count conns;.z.m.loginfo[`servers;"no configured connections to make"];:()]; + if[not `processcsv in key config;raiseerror[`startup;"processcsv (path to process.csv) is required in config to open connections"]]; + procs:readprocesscsv[config`processcsv]; + pt:.z.m.self`proctype; + pn:.z.m.self`procname; + procs:update isme:(proctype=pt)&procname=pn from procs; + procs:select from procs where not isme; + procs:select from procs where proctype in conns; + if[0=count procs;.z.m.loginfo[`servers;"no process.csv rows match the configured connections"];:()]; + {[row] + hpup:formathp[row`host;row`port;`tcp]; + w:opencon[hpup]; + if[not null w;.z.m.loginfo[`servers;"connected to ",(string row`proctype),"/",(string row`procname)," at ",string hpup]]; + / catenate+reassign, NOT `tablename insert - a symbol-based insert into `.z.m.SERVERS` misses + / the compile-time module-local rewrite a source-level .z.m.SERVERS gets, silently targeting the + / wrong (literal) table. + newrow:([]procname:enlist row`procname;proctype:enlist row`proctype;hpup:enlist hpup;w:enlist w;hits:enlist 0i;startp:enlist $[null w;0Np;.z.p];lastp:enlist .z.p;endp:enlist 0Np); + .z.m.SERVERS:.z.m.SERVERS,newrow; + } each 0!procs; + }; + +retryrows:{[rows] + / internal - reattempt opencon for the given SERVERS row indices, updating w/lastp (and startp on + / a successful reconnect). + hs:opencon each exec hpup from .z.m.SERVERS where i in rows; + .z.m.SERVERS:update w:hs,lastp:.z.p from .z.m.SERVERS where i in rows; + .z.m.SERVERS:update startp:.z.p from .z.m.SERVERS where i in rows, not null w; + }; + +cleanup:{[] + / internal - sweep any row whose handle has vanished from key .z.W (a peer that died WITHOUT a + / clean .z.pc on this side) and mark it disconnected, so retry will reopen it. the .z.pc observer + / already catches clean closes; this catches the ungraceful ones. + dead:exec w from .z.m.SERVERS where not null w, not w in key .z.W; + if[count dead;.z.m.SERVERS:update endp:.z.p,w:0Ni from .z.m.SERVERS where w in dead]; + }; + +retry:{[] + / internal - the scheduled `serversretry job (driven by the injected timer; passed by value at + / init, so it needs no export). first sweep ungracefully-vanished handles (cleanup), then reopen + / every dead (null) handle - so both clean and unclean drops are recovered on the retry cycle. + cleanup[]; + rows:exec i from .z.m.SERVERS where null w; + if[count rows;retryrows[rows]]; + }; + +getservers:{[pt] + / every live (non-null handle) SERVERS row for a proctype. + if[not -11h=type pt;raiseerror[`getservers;"proctype must be a symbol"]]; + select from .z.m.SERVERS where proctype=pt, not null w + }; + +selector:{[tab;selection] + / internal - pick one row from a live-server table by algorithm. + $[selection=`roundrobin;first `lastp xasc tab; + selection=`any; rand tab; + selection=`last; last `lastp xasc tab; + raiseerror[`selector;"unknown selection type ",string selection]] + }; + +updatestats:{[wh] + / internal - bump hits/lastp on the row whose handle was just handed out. + .z.m.SERVERS:update lastp:.z.p,hits:1+hits from .z.m.SERVERS where w=wh + }; + +gethandlebytype:{[pt;selection] + / get a single live handle for a proctype via a selection algorithm (`any`roundrobin`last), or + / 0Ni if none is connected. bumps usage stats on the chosen row. + if[not -11h=type pt;raiseerror[`gethandlebytype;"proctype must be a symbol"]]; + if[not -11h=type selection;raiseerror[`gethandlebytype;"selection must be a symbol (`any`roundrobin`last)"]]; + r:getservers[pt]; + if[0=count r;:0Ni]; + wh:(selector[r;selection])`w; + updatestats[wh]; + wh + }; + +signalfound:{[pt] + / internal - log and return 1b once a connection to pt exists. + .z.m.loginfo[`servers;"connected to ",string pt]; + 1b + }; + +waitfortype:{[pt;timeoutms;pollms] + / block until at least one LIVE connection to pt exists, or timeoutms elapses. the DI-scoped + / analogue of legacy TorQ's startupdepcycles - "fail fast, but wait for a hard dependency to come + / up". startup must have run first (so a pt row exists to reattempt). polls retry between tries, + / sleeping pollms. returns 1b once connected, 0b on timeout - the CALLER decides if that is fatal. + / NOTE the blocking system"sleep" is fine at startup (single-threaded; the injected timer's .z.ts + / just doesn't fire during the sleep). + if[not -11h=type pt;raiseerror[`waitfortype;"proctype must be a symbol"]]; + if[not (abs type timeoutms) within 5 7h;raiseerror[`waitfortype;"timeoutms must be an integer (ms)"]]; + if[not (abs type pollms) within 5 7h;raiseerror[`waitfortype;"pollms must be an integer (ms)"]]; + deadline:.z.p+`timespan$1000000*`long$timeoutms; + .z.m.loginfo[`servers;"waiting up to ",(string timeoutms),"ms for a ",(string pt)," connection"]; + while[(0=count getservers pt) and .z.p +/ cleanup, tested in isolation from the auto .z.pc hook (which di.torq.handlers would install for real). +handlercalls:([]event:`symbol$();name:`symbol$()); +mockhandlers:`register`remove`list!( + {[ev;ph;nm;pri;fn]`handlercalls upsert(ev;nm)}; + {[ev;ph;nm]}; + {[ev]}); + +warnlogged:{[s] any (exec msg from logrows where lvl=`warn) like "*",s,"*"}; +firejob:{[id] timerjobs[id][]}; + +/ --- real peer process fixture --- +FIXDIR:"/tmp/diserverstest"; +isfree:{[p] not @[{hclose hopen x;1b};(`$":localhost:",string p;100);0b]}; +pickport:{[start] first (start+til 500) where isfree each start+til 500}; +PEERPORT:0N; DEADPORT:0N; PEERPID:0N; + +waitlisten:{[port;timeoutms] + deadline:.z.p+`timespan$1000000*timeoutms; + while[(.z.p/dev/null 2>&1 &"; + if[not waitlisten[PEERPORT;3000];'"test: peer failed to listen on ",string PEERPORT]; + h:hopen (`$":localhost:",string PEERPORT;2000); + PEERPID::h ".z.i"; + hclose h;}; + +killpeer:{[] if[not null PEERPID;@[system;"kill ",string PEERPID;{}]]; PEERPID::0N; system "sleep 0.3";}; + +setupfixture:{[] + / pick two free ports (peer + a never-listening dead one), then write a header'd process.csv + / phone book with self, the peer (otherproc), and a dead proctype. + PEERPORT::pickport 20000+`int$.z.i mod 20000; + DEADPORT::pickport PEERPORT+1; + system "mkdir -p ",FIXDIR; + (`$":",FIXDIR,"/process.csv") 0: ( + "host,port,proctype,procname"; + "localhost,",string[PEERPORT-2],",selfproc,selfinst"; + "localhost,",string[PEERPORT],",otherproc,otherinst"; + "localhost,",string[DEADPORT],",deadproc,deadinst"); + }; + +teardownfixture:{[] killpeer[]; system "rm -rf ",FIXDIR;}; + +/ build the deps dict di.torq would assemble: injectables + this process's config slice. +svrdeps:{[conns] `log`timer`handlers`proctype`procname`connections`processcsv!(mocklog;mocktimer;mockhandlers;`selfproc;`selfinst;conns;FIXDIR,"/process.csv")}; diff --git a/di/torq/settings/default.q b/di/torq/settings/default.q new file mode 100644 index 00000000..09f96f7f --- /dev/null +++ b/di/torq/settings/default.q @@ -0,0 +1 @@ +/ built-in framework defaults - empty for v0 diff --git a/di/torq/settings/hdb.q b/di/torq/settings/hdb.q new file mode 100644 index 00000000..8369fe78 --- /dev/null +++ b/di/torq/settings/hdb.q @@ -0,0 +1 @@ +dir:`:hdb diff --git a/di/torq/test.csv b/di/torq/test.csv new file mode 100644 index 00000000..31edae85 --- /dev/null +++ b/di/torq/test.csv @@ -0,0 +1,53 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,tq:use`di.torq,1,,load module +before,0,0,q,system "l di/torq/test.q",1,,load fixture helpers +before,0,0,q,setupfixture[],1,,create a temp app fixture: settings, process.csv, scratch hdb, custom proctype file + +fail,0,0,q,tq.reqenv[`DI_TORQ_TEST_NO_SUCH_VAR],1,,reqenv on a missing env var must error + +fail,0,0,q,tq.init[`;`;()!()],1,,"auto-detect with no port set (system""p""=0) and two localhost rows in process.csv must fail as ambiguous" + +run,0,0,q,system "p 19999",1,,bind a port that appears nowhere in the fixture process.csv +fail,0,0,q,tq.init[`;`;()!()],1,,auto-detect must fail when this session's port matches no process.csv row + +run,0,0,q,r:tq.init[`hdb;`hdb;()!()],1,,explicit-identity init for the built-in hdb proctype +true,0,0,q,`hdb~r`proctype,1,,identity resolved from the explicit args +true,0,0,q,`k4unittest~(r`config)`owner,1,,config cascade reached the app-level default.q +true,0,0,q,`widgets in tables[],1,,the built-in hdb module actually mounted the fixture hdb dir +true,0,0,q,(`handlers`log`servers`timer)~asc key r`deps,1,,all four core deps (incl injected servers) were built and passed through + +run,0,0,q,r2:tq.init[`hdb;`hdb;enlist[`log]!enlist`di.util.log],1,,init with an explicit (if trivial) log override still works +true,0,0,q,`hdb~r2`proctype,1,,override path still resolves the same identity + +run,0,0,q,r3:tq.init[TESTPROCNAME;`testinst;()!()],1,,explicit-identity init for a custom proctype +true,0,0,q,TESTPROCNAME~r3`proctype,1,,identity resolved for the custom proctype +true,0,0,q,`widget in key .k4unittestproc.capturedconfig,1,,config cascade reached the custom proctype's own settings file +true,0,0,q,(`handlers`log`servers`timer)~asc key .k4unittestproc.captureddeps,1,,deps (incl injected servers) were passed through to the custom proctype's init exactly like a built-in one +true,0,0,q,1=.k4unittestproc.runcalled,1,,the .run hook fired automatically after init - no launcher-side proctype knowledge needed + +run,0,0,q,r5:tq.init[TESTPROCNAME;`testinst;enlist[`norun]!enlist 1b],1,,re-init with the norun override set (this reloads the proctype file, resetting runcalled to 0) +true,0,0,q,0=.k4unittestproc.runcalled,1,,-norun skipped the hook - count stayed at 0 instead of incrementing to 1 + +true,0,0,q,APPCOMMON_LOADED,1,,app-code cascade loaded code/common/*.q during init (at root) +true,0,0,q,APPPROC_LOADED,1,,app-code cascade loaded code//*.q during init (at root) +true,0,0,q,not `APPNAME_LOADED in key `.,1,,procname-tier code// is OFF by default (loadnamecode) +run,0,0,q,enablenamecode[],1,,enable procname-tier loading via the procname settings tier +run,0,0,q,r6:tq.init[TESTPROCNAME;`testinst;enlist[`norun]!enlist 1b],1,,re-init with loadnamecode turned on in config +true,0,0,q,`APPNAME_LOADED in key `.,1,,procname-tier code now loads when loadnamecode=1b + +true,0,0,q,`hdb~r`proctype,1,,sanity: hdb (no .hdb.run published) still inited cleanly earlier with no hook and no error + +run,0,0,q,system "p 28580",1,,rebind to the port process.csv says hdb owns +run,0,0,q,r4:tq.init[`;`;()!()],1,,auto-detect identity now that the port uniquely matches one row +true,0,0,q,`hdb~r4`proctype,1,,auto-detected the right proctype +true,0,0,q,`hdb~r4`procname,1,,auto-detected the right procname + +comment,,,,,,,command-line override layer - clioverrideparams filters .Q.opt .z.x into config-override params +run,0,0,q,cliopts:sampleopts[],1,,a synthetic .Q.opt-shape command line (reserved launcher flags + myrows/myname setting flags) +true,0,0,q,`myname`myrows~asc key .m.di.0torq.clioverrideparams[cliopts],1,,only the real setting flags survive the filter +true,0,0,q,not any `proctype`procname`torqxstackid`p`norun in key .m.di.0torq.clioverrideparams[cliopts],1,,every reserved launcher/identity flag is dropped before overrideconfig +true,0,0,q,(enlist"7")~(.m.di.0torq.clioverrideparams[cliopts])`myrows,1,,kept override values are unchanged (the .Q.opt string-list shape overrideconfig expects) +true,0,0,q,0=count .m.di.0torq.clioverrideparams[()!()],1,,an empty command line yields no overrides +true,0,0,q,0=count .m.di.0torq.clioverrideparams[`proctype`p!((enlist"hdb");(enlist"5560"))],1,,a command line of only reserved flags yields no overrides + +after,0,0,q,teardownfixture[],1,,remove the temp app fixture and the temp custom-proctype file diff --git a/di/torq/test.q b/di/torq/test.q new file mode 100644 index 00000000..176d846f --- /dev/null +++ b/di/torq/test.q @@ -0,0 +1,73 @@ +/ fixture helpers for di.torq's tests. +/ Assumes q is started with the TorqX repo root as the working directory AND with +/ TORQXHOME already pointing at the real TorqX checkout (di.torq's own built-in +/ settings and `builtin` registry genuinely live there - there is no faking that part). +/ TORQXAPPCONFIG and TORQXAPPHOME are both repointed at a temp fixture below to +/ isolate everything else (process.csv, app-level settings, a scratch hdb dir, the +/ custom proctype's code file) from any real app - nothing this test does touches a +/ real app directory. Uses real di.util.log/di.timer/di.torq.handlers/di.proc.hdb throughout rather than +/ mocking them - they are each already covered by their own module's tests, and +/ di.torq's job is to wire them together correctly, which mocking them away would not +/ actually test. + +APPBASE:"/tmp/di_torq_k4unit_app" +HDBDIR:APPBASE,"/hdb" +TESTPROCNAME:`k4unittestproc +TESTPROCFILE:APPBASE,"/code/processes/",string[TESTPROCNAME],".q" + +writelines:{[path;lines] (hsym `$path) 0: lines; } + +setupfixture:{[] + system "rm -rf ",APPBASE; + system "mkdir -p ",APPBASE,"/settings ",APPBASE,"/code/processes ",APPBASE,"/code/common ",APPBASE,"/code/",string[TESTPROCNAME]," ",APPBASE,"/code/testinst ",HDBDIR; + setenv[`TORQXAPPCONFIG;APPBASE]; + setenv[`TORQXAPPHOME;APPBASE]; + + / app-code cascade markers: a bare file (no \d) in each tier dir sets a root flag when loaded, + / so tests can assert which tiers di.torq's loadappcode picked up (common -> proctype -> procname). + writelines[APPBASE,"/code/common/appcommon.q";enlist "APPCOMMON_LOADED:1b"]; + writelines[APPBASE,"/code/",string[TESTPROCNAME],"/appproc.q";enlist "APPPROC_LOADED:1b"]; + writelines[APPBASE,"/code/testinst/appname.q";enlist "APPNAME_LOADED:1b"]; + + / a scratch hdb: just a serialized table, the simplest thing \l can load + (hsym `$HDBDIR,"/widgets") set ([]id:1 2 3); + + writelines[APPBASE,"/settings/default.q";enlist "owner:`k4unittest"]; + writelines[APPBASE,"/settings/hdb.q";enlist "dir:`:",HDBDIR]; + writelines[APPBASE,"/settings/",string[TESTPROCNAME],".q";enlist "widget:1"]; + + writelines[APPBASE,"/process.csv"; + ("host,port,proctype,procname"; + "localhost,28580,hdb,hdb"; + "localhost,0,",(string TESTPROCNAME),",testinst")]; + + / a trivial custom process type - mirrors code/processes/loader.q's shape, but just + / captures what it was called with so the test can assert on it. Also publishes a + / `run` hook (di.torq's optional post-init convention, see torq.q's runhook) that + / just counts how many times it fired, so tests can assert it ran/didn't run. + writelines[TESTPROCFILE; + ("\\d .",string TESTPROCNAME; + "runcalled:0;"; + "init:{[config;deps]"; + " capturedconfig::config;"; + " captureddeps::deps;"; + " deps[`log][`info][`",(string TESTPROCNAME),";\"custom proctype initialised\"];"; + " };"; + "run:{[] runcalled::runcalled+1};"; + "\\d .")]; + } + +/ helper so the test.csv cell stays comma-free (k4unit's CSV splits unquoted commas): writes +/ loadnamecode into the procname settings tier to turn on the procname-tier app-code cascade. +enablenamecode:{[] writelines[APPBASE,"/settings/testinst.q";enlist "loadnamecode:1b"]; } + +/ a synthetic parsed-command-line opt dict in .Q.opt shape (values are string lists; a bare flag +/ like -norun is ()) for the command-line override-layer tests. Mixes the reserved launcher/identity +/ flags di.torq consumes (proctype/procname/torqxstackid/p/norun) with two real setting flags +/ (myrows/myname), so a test can assert clioverrideparams keeps only the latter. +sampleopts:{[] `proctype`procname`torqxstackid`p`norun`myrows`myname!((enlist"hdb");(enlist"hdb");(enlist"s1");(enlist"5560");();(enlist"7");(enlist"widget"))} + +teardownfixture:{[] + system "rm -rf ",APPBASE; + system "rm -f ",TESTPROCFILE; + } diff --git a/di/torq/torq.md b/di/torq/torq.md new file mode 100644 index 00000000..5727be94 --- /dev/null +++ b/di/torq/torq.md @@ -0,0 +1,264 @@ +# di.torq + +The process orchestrator - the single entry point every TorqX process goes through, +whether it's a built-in process type (a `di.*` module, like `di.proc.hdb`) or a custom one +(a plain file under the app's own `code/processes/`). Resolves who this process is, +builds its config from the settings cascade, builds its injected dependencies, and +starts the right process type - all through one call: `init[proctype;procname; +overrides]`. + +This is TorqX's analogue of legacy TorQ's `torq.q`, but narrower in scope: the +launcher-side responsibilities (parsing a command line, actually starting a q +process, supervising start/stop across a whole `process.csv`) live in +`TorqX/di/torq/bin/torqx_init.q` and `TorqX/di/torq/bin/torqx.sh` instead - two deliberately thin +files that call into `di.torq.init` rather than duplicating what it does. Everything +below is `di.torq`'s own job; see the note at the end for how the launcher fits in. + +## Design + +### Identity resolution + +`init`'s first job is figuring out `proctype`/`procname`, via `resolveidentity`: + +```q +resolveidentity:{[proctype;procname] + $[(null proctype) or (null procname); + autodetect[]; + `proctype`procname!(proctype;procname)] + } +``` + +Both-or-neither - there's no partial mode where one is given explicitly and the other +auto-detected. If either is null, `autodetect[]` reads `process.csv` (from +`TORQXAPPCONFIG`) and matches it against this session's own listening port +(`` system"p" ``), with host as a tiebreaker (own hostname → own IP → `` `localhost ``, +case-insensitive) - ported from legacy TorQ's `torq.q`'s `readprocfile`, scoped down +(no envvar substitution in the CSV, no `-procfile` override, no FinSpace host +handling). If autodetection narrows to exactly one candidate and no port was given yet +(`` system"p" `` was `0i`), `autodetect` binds the port itself (`` system"p ",string +port ``) rather than requiring it to already be set - so `torqx -p 5560` alone is +enough, you don't have to separately track which port belongs to which row. + +Fails fast, with a specific message, in both ambiguous cases: + +```q +q)tq.init[`;`;()!()] +'di.torq: cannot auto-detect identity - 2 process.csv rows match this host with no port to disambiguate; pass -p or proctype/procname explicitly +``` + +(or `"...no process.csv row matches this host"` if the port/host combination matches +nothing at all). + +### Environment variables + +Three independent, explicitly-set env vars - not derived from each other: + +| var | what it points at | used for | +|---|---|---| +| `TORQXHOME` | the `di.torq`/framework checkout | builtin settings root (`$TORQXHOME/di/torq/settings`) | +| `TORQXAPPCONFIG` | the app's `appconfig/` directory | app settings root (`$TORQXAPPCONFIG/settings`) and `process.csv` | +| `TORQXAPPHOME` | the app's own project root | `code/processes/{proctype}.q` (custom proctypes), and where `di.proc.hdb`'s relative `dir:` settings resolve against | + +### Config cascade + +`roots[]` builds the two roots `di.torq.config.cascade` needs +(`` `$TORQXHOME/di/torq/settings ``, `` `$TORQXAPPCONFIG/settings ``); `init` calls +`` (cc`cascade)[r 0;r 1;proctype;procname] `` and then adds the resolved +`proctype`/`procname` into the result itself, so any module (or anything it calls) +can find out who it is just by looking at its own `config` dict - no global to reach +for. See `di.torq.config`'s own docs for the 5-tier cascade itself. + +### Dependency building + +`buildlogdep`/`buildtimerdep`/`buildhandlersdep` each build one of the three DI +contract dependencies (`log`, `timer`, `handlers`), defaulting to `di.util.log`/`di.timer`/ +`di.torq.handlers` respectively, with an override escape hatch - the `overrides` dict passed +into `init` can specify a different module name under the `` `log ``/`` `timer ``/ +`` `handlers `` key. `buildtimerdep` also initializes `di.timer` itself (with no deps +of its own - it's Tier 1 standalone) and reshapes its exported `addjob` (a dict of +`custom`/`default`/`simple` variants) down to the one signature the DI contract +expects. + +### Process-type dispatch + +A small built-in registry maps proctype → module name: + +```q +builtin:(enlist`hdb)!enlist`di.proc.hdb +``` + +If `proctype` is in `builtin`, `startbuiltin` `use`-loads that module and calls its +`init[config;deps]`. Otherwise `startcustom` loads +`` $TORQXAPPHOME/code/processes/{proctype}.q `` directly (a plain `system "l ..."`, +not `use` - custom proctypes aren't kdb-x modules, they're app code, so there's no +namespace-mangling to work around) and calls `` .{proctype}.init[config;deps] ``. +Both paths call the exact same `init[config;deps]` shape either way - a custom +proctype is indistinguishable from a built-in one from `di.torq`'s point of view. + +### Application code cascade + +After the process type is started, `init` calls `loadappcode[lg;config;proctype;procname]` +to load any add-on q scripts the **app** drops under `` $TORQXAPPHOME/code// ``. This is +the modular equivalent of TorQ's `.proc.reloadallcode` (`torq.q`) — but scaled to a **single +app code root**: the TorqX framework ships behaviour as `di.*` *modules* (loaded via `use`), so +there is no framework `code/` tree to cascade over, only the app's. + +The cascade mirrors the config cascade's shape: + +| tier | directory | flag | default | +|------|-----------|------|---------| +| common | `code/common/` | `loadcommoncode` | on | +| proctype | `code//` | `loadprocesscode` | on | +| procname | `code//` | `loadnamecode` | **off** | + +So **yes, it supports per-procname customisation** just like the config cascade — but, exactly +as in TorQ (`.proc.loadnamecode` defaults `0b`), the procname tier is **off by default** and +opt-in via `loadnamecode:1b` in that process's settings. Each flag is read from the merged +config (so it's overridable per-process in settings). `parentproctype` (TorQ's 4th tier, for +sharing code between a WDB and its sort workers) is omitted — there is no sort-worker tier yet. + +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`. +A missing directory is a silent no-op. Files are loaded with a **plain `system "l"` (not `use`)**, +so their definitions land in whatever namespace their own `\d` directives choose: a bare app +query file like `code/rdb/examplequeries.q` (no `\d`) lands at **root**, callable as +`countbysym[…]` — which is the whole point (the tickerplant can't call a module-mangled `upd`, +and an operator can't call a mangled query fn). This is the same load mechanism `startcustom` +already uses for `code/processes/`. + +App code loads **after** the process module's `init` (so it can reference the module's tables and +state) and **before** the `.run` hook (so an app file may define/override `` ..run ``). + +### The `.run` post-init hook + +After starting the process type and loading app code, `init` calls `runhook[proctype;overrides]`: + +```q +runhook:{[proctype;overrides] + if[`norun in key overrides;if[overrides`norun;:()]]; + ns:`$".",string proctype; + if[`run in key ns;(get `$".",(string proctype),".run")[]]; + } +``` + +If the process type published a `` .{proctype}.run `` function - the same +"publish at a real root name" convention `di.proc.hdb` uses for `.hdb.reload` - it gets +called automatically, with no proctype-specific knowledge anywhere in `di.torq` +itself, the launcher, or `torqx.sh`. This exists so a process type can have its own +one-shot startup action (the sample loader's `loadall` - aliased as `run:loadall` in +`code/processes/loader.q` - reads its landing directory and loads it, right after +init) without the generic launcher needing to know that loaders, specifically, need +an extra call after `init` that hdb processes don't. Skipped entirely if +`overrides[`norun]` is set - see `di/torq/bin/torqx_init.q`'s `-norun` flag. + +## Usage + +```q +q)tq:use`di.torq +q)r:tq.init[`hdb;`hdb;()!()] +2026.07.09D12:48:40.352242000 INFO hdb mounting hdb from :/Users/jgrant/git/TorqX-POC/hdb +2026.07.09D12:48:40.355727000 INFO hdb loaded tables: trade +q)r`proctype +`hdb +q)key r`config +`dir`connections`proctype`procname +q)key r`deps +`log`timer`handlers +q)tables[] +,`trade +``` + +Auto-detected identity, once the session is listening on the right port: + +```q +q)system "p 5560" +q)r:tq.init[`;`;()!()] +2026.07.09D12:48:48.864626000 INFO hdb mounting hdb from :/Users/jgrant/git/TorqX-POC/hdb +2026.07.09D12:48:48.864819000 INFO hdb loaded tables: trade +q)r`proctype +`hdb +q)r`procname +`hdb +``` + +The `overrides` dict recognizes four keys, all optional: + +| key | effect | +|---|---| +| `log` | use this module instead of `di.util.log` for the `log` dependency | +| `timer` | use this module instead of `di.timer` for the `timer` dependency | +| `handlers` | use this module instead of `di.torq.handlers` for the `handlers` dependency | +| `norun` | if truthy, skip the `.{proctype}.run` post-init hook even if one exists | + +### How the launcher fits in + +In practice nothing calls `tq.init` directly like the examples above - that's what +`di/torq/bin/torqx_init.q` (a tiny QINIT-loaded script) does, parsing `-proctype`/`-procname`/ +`-norun` off the command line and calling `init` with them, and what `di/torq/bin/torqx.sh` +does on top of that (start/stop/restart/status across a whole `process.csv`, without +duplicating any of the identity-resolution logic above - it only reads `process.csv` +to know *which* processes exist, never to resolve *who a given session is*, which +stays exclusively `di.torq`'s job). + +### Dev mode (tmux) + +`torqx.sh start` normally launches each process as a background `nohup` process +redirecting to a logfile. Passing `--tmux` (or `-t`) instead runs each process inside a +detached, **attachable tmux session** - one session per process, named +`-` (e.g. `torqx-poc-rdb1`) - so a developer can attach to a +live `q)` console for any process: + +``` +torqx.sh start rdb1 --tmux # or the alias: torqx.sh devstart rdb1 +torqx.sh attach rdb1 # attach to the q) console (or: tmux attach -t torqx-poc-rdb1) +torqx.sh status # tags tmux-managed procs with "(tmux)" +torqx.sh stop rdb1 # kills the process and cleans up its tmux session +``` + +`devstart`/`devstop`/`devattach` are aliases for `start --tmux`/`stop`/`attach`. The +tmux path keeps the *same* `-torqxstackid/-proctype/-procname` command-line signature as +the `nohup` path, so `stop`/`status` (which discover processes via `pgrep`) work +identically regardless of how a process was started. The pane keeps a crashed process +visible (`remain-on-exit`) and still tees output to the usual logfile (`pipe-pane`). It +re-sources `setenv.sh` inside the pane (via `bash -c`, **not** a login shell - a login +shell would source the user's profile and can inject a stale `QHOME`) so the process gets +the right environment even when a tmux server is already running, and it reproduces +torqx.sh's exact `QHOME`/`QLIC` in the pane (passed through if set, forced unset otherwise) +so q's licence resolution - including the common "infer `QHOME` from the q binary's +location" setup - matches the nohup path. Starting a process (either mode) first clears any +lingering tmux session for it, so a crashed `remain-on-exit` pane never coexists with a +freshly-started process. tmux mode is for local development; production stays on +`export-systemd`. + +## Known gaps (v1) + +- The builtin registry has exactly one entry (`` `hdb ``) so far - every other + proctype in a real deployment would be custom, until more `di.*` process-type + modules exist. +- No `di.torq.depcheck`-style pre-flight dependency validation yet (next up per the + modularisation plan). +- `autodetect`'s host-matching has no `-procfile` override and no FinSpace-specific + host handling - deliberately out of scope, same scoping-down `di.torq.servers` applies + to its own `process.csv` reading. + +## Testing + +`test.csv`/`test.q` (k4unit) deliberately use the **real** `di.util.log`/`di.timer`/ +`di.torq.handlers`/`di.proc.hdb` rather than mocks - each of those is already covered by its own +module's tests, and `di.torq`'s actual job is wiring them together correctly, which +mocking them away wouldn't exercise. Only `TORQXAPPCONFIG`/`TORQXAPPHOME` are +repointed at a temp fixture (a scratch settings tree, `process.csv`, and a throwaway +custom proctype file that publishes its own `run` hook to assert on) - `TORQXHOME` +stays real, since `di.torq`'s own built-in settings and registry genuinely live +there. Covers: `reqenv` erroring on a missing var, both auto-detect failure modes +(no match, ambiguous), explicit-identity init for both a built-in and a custom +proctype, config-cascade/deps reaching the started process type correctly, the +`.run` hook firing by default and being skipped when `norun` is set, and successful +auto-detection once the ambiguity is resolved. Run in a fresh q session (mutates +`system"p"` and `TORQXAPPCONFIG`/`TORQXAPPHOME`, don't interleave with other +modules' tests): + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.torq +``` diff --git a/di/torq/torq.q b/di/torq/torq.q new file mode 100644 index 00000000..efb43df8 --- /dev/null +++ b/di/torq/torq.q @@ -0,0 +1,255 @@ +/ di.torq - process orchestrator. Resolves config via the settings cascade, builds +/ the injected-dependency dict, and starts either a built-in (di.*) process module or +/ a custom one supplied by the app's code/processes/ directory - both through the +/ same init[config;deps] calling convention. + +/ built-in process type registry: proctype -> di.* module name +builtin:`hdb`tickerplant`rdb`wdb`gateway!`di.proc.hdb`di.proc.tickerplant`di.proc.rdb`di.proc.wdb`di.proc.gateway + +reqenv:{[e] + v:getenv e; + if[""~v;'"di.torq: required environment variable ",(string e)," is not set"]; + v + } + +roots:{ + builtinroot:reqenv[`TORQXHOME],"/di/torq/settings"; + approot:reqenv[`TORQXAPPCONFIG],"/settings"; + (builtinroot;approot) + } + +/ resolves this process's identity: explicit args if both given, otherwise auto-detected +/ from process.csv by matching this session's listening port (and, as a tiebreaker, its +/ host) - ported from TorQ/torq.q's readprocfile, scoped down (no envvar substitution in +/ the csv, no -procfile override, no finspace host handling). Both-or-neither only - no +/ partial mode where one of proctype/procname is given and the other auto-detected. +resolveidentity:{[proctype;procname] + / NOTE: q evaluates right-to-left with flat precedence - `not a or b` parses as + / `not[a or b]`, not `(not a) or b`. Written as `(null x) or (null y)` directly instead + / of negating a fenced-off "both given" test, to avoid that trap. + $[(null proctype) or (null procname); + autodetect[]; + `proctype`procname!(proctype;procname)] + } + +/ NOTE: deliberately does not reuse di.torq.servers.readprocesscsv - di.torq shouldn't have +/ to load di.torq.servers just to boot. Small duplication; extract to a shared helper if a +/ third consumer of process.csv ever shows up. +autodetect:{[] + path:reqenv[`TORQXAPPCONFIG],"/process.csv"; + fsym:`$":",path; + if[0=count key fsym;'"di.torq: cannot auto-detect identity - process.csv not found at ",path]; + procs:("SISS";enlist",") 0: fsym; + procs:select from procs where not null host; + myport:system "p"; + cands:$[myport=0i;procs;select from procs where abs[port]=abs myport]; + myip:`$"." sv string "i"$0x0 vs .z.a; + prefs:(`$lower string .z.h;`$lower string myip;`localhost); + cands:update hlow:`$lower each string host from cands; + cands:select from cands where hlow in prefs; + if[0=count cands; + '"di.torq: cannot auto-detect identity - no process.csv row matches this host",$[myport=0i;"";" and port ",string myport]]; + if[(1remove aliasing as the earlier TorqX module needed. +buildhandlersdep:{[overrides;logdep] + modname:$[`handlers in key overrides;overrides`handlers;`di.torq.handlers]; + hz:use modname; + (hz`init)[enlist[`log]!enlist logdep]; + `register`remove`list!(hz`register;hz`remove;hz`list) + } + +/ builds the servers (connection-management) dependency dict, using di.torq.servers unless +/ overridden. Unlike log/timer/handlers, di.torq.servers is itself a CONSUMER of those three - +/ its init registers a .z.pc cleanup handler (via handlers) and a reconnection retry timer +/ job (via timer), and stamps self-identity from config`proctype`/`procname - so it is built +/ LAST, after all three exist. Exposes only the lookup/lifecycle surface consumers call; +/ `init` is deliberately NOT re-exported - di.torq has already run it, and a second init would +/ double-register the pc handler and the retry job (the exact fragility that motivated +/ promoting servers from a per-module `use`+init to an injected singleton). `startup` IS +/ exposed: it opens the actual connections and is called by each consumer with its own +/ `connections` list, so connection-opening timing stays with the consumer. +/ NB every process gets an init'd servers instance, even ones that never dial out +/ (hdb/tickerplant): harmless - the registry starts empty, the pc handler and the retry job +/ are no-ops on an empty SERVERS table, and startup (the part that opens sockets) is never +/ called. Prune per-proctype if/when a capabilities declaration lands (see servers.md). +/ NB local is `srv` not `sv` - `sv` is the built-in scalar-from-vector/join operator and +/ won't reliably shadow as a local (same reserved-name trap as `log`/`ss` noted in project +/ memory); assigning it here threw '`sv` at module load. +buildserversdep:{[overrides;config;logdep;timerdep;handlersdep] + modname:$[`servers in key overrides;overrides`servers;`di.torq.servers]; + srv:use modname; + / one-arg init[deps] (kdbx convention, matching handlers/config/depcheck): merge the injectables into + / this process's config slice - init reads log/timer/handlers + proctype/procname self-identity from it. + (srv`init)[config,`log`timer`handlers!(logdep;timerdep;handlersdep)]; + `startup`getservers`gethandlebytype`waitfortype!((srv`startup);(srv`getservers);(srv`gethandlebytype);(srv`waitfortype)) + } + +/ starts a built-in process type, shipped as a di.* module +startbuiltin:{[proctype;config;deps] + m:use builtin proctype; + (m`init)[config;deps] + } + +/ starts a custom process type, defined by the app under code/processes/{proctype}.q +/ (code/ lives alongside appconfig/ under TORQXAPPHOME, the app's own project root - +/ independent of TORQXHOME, which is the di.torq/framework checkout) +startcustom:{[proctype;config;deps] + appbase:reqenv[`TORQXAPPHOME]; + procfile:appbase,"/code/processes/",(string proctype),".q"; + system "l ",procfile; + initfunc:get `$".",(string proctype),".init"; + initfunc[config;deps] + } + +/ --- application code cascade (TorQ-style) ------------------------------------------------ +/ Loads add-on q scripts the APP drops under $TORQXAPPHOME/code// for a process, mirroring +/ torq.q's .proc.reloadallcode but scaled to the SINGLE app code root: the TorqX framework ships +/ behaviour as di.* MODULES (loaded via `use`), not code/ dirs, so there is no framework +/ code root to cascade over - only the app's. Cascade order mirrors the config cascade and torq.q: +/ common -> proctype -> procname, procname OFF by default (matching torq.q's loadnamecode). Flags +/ (from the merged config, per-process overridable in settings): loadcommoncode / loadprocesscode / +/ loadnamecode. Deliberately NOT via `use` (which mangles a module into a private namespace): a +/ 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.) +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 +/ the rest alphabetically. Absent/empty dir -> no-op (key on a missing path returns empty). +/ (param is `lg` not `log` - `log` is the built-in natural-log and won't reliably shadow.) +loadappcodedir:{[lg;dir] + files:key hsym `$dir; + if[0=count files;:()]; + ord:$[`order.txt in files;(`$read0 hsym `$dir,"/order.txt") inter files;`symbol$()]; + qk:asc files where any files like/:("*.q";"*.k"); + {[lg;dir;f] p:dir,"/",string f; system "l ",p; lg[`info][`torq;"loaded app code ",p]}[lg;dir] each ord,qk except ord; + } + +loadappcode:{[lg;config;proctype;procname] + base:reqenv[`TORQXAPPHOME],"/code/"; + if[optflag[config;`loadcommoncode;1b]; loadappcodedir[lg;base,"common"]]; + if[optflag[config;`loadprocesscode;1b]; loadappcodedir[lg;base,string proctype]]; + if[optflag[config;`loadnamecode;0b]; loadappcodedir[lg;base,string procname]]; + } + +/ calls an optional post-init one-shot hook, .{proctype}.run[], if the process type +/ published one - same "publish at a real root name" convention already used for +/ .hdb.reload (custom proctypes under code/processes/ land there for free via their +/ own \d .proctype block; a built-in di.* module must explicitly set[`.X.run;...] since +/ use mangles its own namespace). Lets a process type (e.g. the sample loader) run its +/ own startup action without the generic launcher needing any proctype-specific logic. +/ Skipped entirely if the overrides dict's `norun key is set - the launcher's -norun +/ escape hatch threads through here. +runhook:{[proctype;overrides] + if[`norun in key overrides;if[overrides`norun;:()]]; + ns:`$".",string proctype; + if[`run in key ns;(get `$".",(string proctype),".run")[]]; + } + +/ reserved launcher/identity flags parsed from the command line - consumed by the launcher and by +/ di.torq itself (identity, stack id, port, norun), NOT config settings. Everything else on the +/ command line is a candidate config override. +reservedflags:`proctype`procname`torqxstackid`p`norun; + +/ the config-override params from a parsed command-line opt dict (.Q.opt .z.x): drop the reserved +/ flags, keep the rest. di.torq.config.overrideconfig then applies each to the matching setting +/ (parsed into its type) and skips any that don't name a real setting. Pure - unit-testable without .z.x. +clioverrideparams:{[cmdlineopts] (key[cmdlineopts] except reservedflags)#cmdlineopts} + +init:{[proctype;procname;overrides] + / dependency check runs first, before anything else - a version mismatch should + / be caught before identity resolution, config, or any module load even starts. + / checkversiongraphfile[] is a no-op if TORQXAPPHOME has no deps.toml (opt-in, see di.torq.depcheck's docs). + dc:use`di.torq.depcheck; + (dc`checkversiongraphfile)[`;reqenv[`TORQXAPPHOME],"/deps.toml"]; + ident:resolveidentity[proctype;procname]; + proctype:ident`proctype; + procname:ident`procname; + / pre-load VERSION graph (reconciled di.torq.depcheck: kdbx's semver + manifest reading, TorqX's on-disk + / VERSION-file walk - see docs/reconciliation/depcheck.md): now that identity is known, walk THIS process's + / dependency subtree - each module's own deps.q/deps.toml declares the minimum versions of the modules it + / `use`s, validated transitively against the VERSION files installed on QPATH. Turns "customer upgraded + / di.proc.gateway but not the di.serverselect it now needs" from a cryptic mid-startup runtime error into a + / clear startup failure naming the culprit. Built-in proctypes have a di.* entry module; a custom proctype's + / optional manifest lives at code/processes/.deps.toml. Pure on-disk reads, still before any module loads. + $[proctype in key builtin; + (dc`checkversiongraph)[enlist builtin proctype]; + (dc`checkversiongraphfile)[proctype;reqenv[`TORQXAPPHOME],"/code/processes/",(string proctype),".deps.toml"]]; + r:roots[]; + / the logger is built before config so di.torq.config's command-line override layer (below) can log through it + logdep:buildlogdep[overrides]; + cc:use`di.torq.config; + (cc`init)[enlist[`log]!enlist logdep]; + config:(cc`cascade)[r 0;r 1;proctype;procname]; + / command-line override layer - the TOP cascade tier. A launch flag matching a settings name + / overrides it (parsed into that setting's type); reserved launcher/identity flags are excluded, + / and a flag that doesn't name a real setting is skipped (see di.torq.config.overrideconfig). + config:(cc`overrideconfig)[config; clioverrideparams .Q.opt .z.x]; + / self-identity is resolved by di.torq and authoritative - stamped AFTER overrides so it always wins + config:config,`proctype`procname!(proctype;procname); + / the process.csv phone-book path, so di.torq.servers (and any consumer building its own startup config + / slice from this config) can dial peers without reading env itself - keeps di.servers' env-free boundary. + config:config,enlist[`processcsv]!enlist reqenv[`TORQXAPPCONFIG],"/process.csv"; + timerdep:buildtimerdep[overrides]; + handlersdep:buildhandlersdep[overrides;logdep]; + / servers is built LAST (it consumes log/timer/handlers at init) and injected alongside + / them, so consumers read deps`servers instead of `use`+init-ing di.torq.servers themselves. + deps:`log`timer`handlers`servers!(logdep;timerdep;handlersdep;buildserversdep[overrides;config;logdep;timerdep;handlersdep]); + / optional, config-driven (see di.torq.logroll's docs) - a silent no-op unless the + / process's settings have a [logroll] section with enabled=true. Called before + / startbuiltin/startcustom so the process type's own init-time log lines land in + / the rolled files too, matching torq.q's own ordering. + lr:use`di.torq.logroll; + (lr`init)[config;deps]; + $[proctype in key builtin; + startbuiltin[proctype;config;deps]; + startcustom[proctype;config;deps] + ]; + / app-level add-on code (code//*.q) - loaded AFTER the process + / module init (so it can reference the module's tables/state) and BEFORE runhook (so an + / app file may define/override ..run for the hook to pick up). + loadappcode[logdep;config;proctype;procname]; + / post-load session audit (di.torq.depcheck.init): now that every module is loaded, introspect the live + / session - core-dependency contract shapes (log/timer/handlers), .z.ts ownership, and an optional minimum + / kdb-x engine version (config`minkdbxversion). Complements the pre-load VERSION graph above, which validated + / installed versions before loading; this validates what actually loaded. Raises on a real contract/dependency gap. + (dc`init)[`log`minkdbxversion!(logdep;$[`minkdbxversion in key config;"f"$config`minkdbxversion;0Nf])]; + runhook[proctype;overrides]; + `proctype`procname`config`deps!(proctype;procname;config;deps) + } diff --git a/di/tplogmgr/VERSION b/di/tplogmgr/VERSION new file mode 100644 index 00000000..6c6aa7cb --- /dev/null +++ b/di/tplogmgr/VERSION @@ -0,0 +1 @@ +0.1.0 \ No newline at end of file diff --git a/di/tplogmgr/init.q b/di/tplogmgr/init.q new file mode 100644 index 00000000..0ed67c3f --- /dev/null +++ b/di/tplogmgr/init.q @@ -0,0 +1,5 @@ +\l ::tplogmgr.q + +version:first read0`:::VERSION + +export:([open;write;roll;replay;replayupto;check;repair;logname;version]) diff --git a/di/tplogmgr/test.csv b/di/tplogmgr/test.csv new file mode 100644 index 00000000..ac19a74e --- /dev/null +++ b/di/tplogmgr/test.csv @@ -0,0 +1,24 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,tp:use`di.tplogmgr,1,,load module +before,0,0,q,system "l di/tplogmgr/test.q",1,,load fixture helpers +before,0,0,q,setupfixture[],1,,create temp fixture dirs + +run,0,0,q,dowriteandreopen[],1,,open fresh + write two + reopen (replays through root upd) +true,0,0,q,0=FRESHCOUNT,1,,a freshly created log has zero messages +true,0,0,q,2=REOPENCOUNT,1,,reopening replays and reports the two written messages +true,0,0,q,2=count replayed,1,,both messages were replayed through the root upd +true,0,0,q,`trade=first first replayed,1,,the replayed message carried the correct table name + +run,0,0,q,rollok:dorollnewfile[],1,,roll closes the current log and opens the next day's +true,0,0,q,rollok,1,,the next day's log file exists after a roll + +fail,0,0,q,opencorrupt[],1,,opening a corrupt log fails fast rather than partially replaying + +run,0,0,q,repok:replaynodouble[],1,,replay repairs a corrupt log and processes each good message once +true,0,0,q,repok,1,,replay executed the root upd exactly once per recovered message (no double-processing) + +true,0,0,q,checkcleanok[],1,,check on a clean log returns the same file unchanged + +true,0,0,q,replayuptopartial[],1,,replayupto replays only the first n messages (not later live-and-logged ones) + +after,0,0,q,teardownfixture[],1,,remove the temp fixture dirs diff --git a/di/tplogmgr/test.q b/di/tplogmgr/test.q new file mode 100644 index 00000000..4cb4c0f3 --- /dev/null +++ b/di/tplogmgr/test.q @@ -0,0 +1,90 @@ +/ fixture helpers for di.tplogmgr's tests. Assumes cwd is the TorqX repo root. +/ di.tplogmgr's open/replay execute the ROOT-level `upd` for each replayed message, so a +/ recorder `upd` is defined here at root. Message tuples contain commas/backticks, so +/ they are built in helpers, never inline in test.csv (raw commas break CSV fields). + +BASE:"/tmp/di_tplog_k4unit" +D:2026.07.13 + +replayed:() +resetreplayed:{[] `replayed set (); } +upd:{[t;x] `replayed set replayed,enlist(t;x); } + +/ a single trade message matching TorqX-POC's database.q trade schema +trademsg:{[ts;s] (`upd;`trade;(enlist ts;enlist s;enlist 1.0;enlist 100i;enlist 0b;enlist" ";enlist"N";enlist`buy))} + +setupfixture:{[] + system "rm -rf ",BASE; + {system "mkdir -p ",BASE,"/",x} each ("main";"roll";"corr";"rep"); + } +teardownfixture:{[] system "rm -rf ",BASE; } + +maindir:{[] BASE,"/main"} + +/ open fresh (stores FRESHCOUNT), write two trades, close; reopen (stores REOPENCOUNT +/ and repopulates `replayed via the root upd during replay). +dowriteandreopen:{[] + resetreplayed[]; + r:tp[`open][maindir[];D]; h:r 0; + `FRESHCOUNT set r 1; + tp[`write][h;trademsg[2026.07.13D10:00;`AAPL]]; + tp[`write][h;trademsg[2026.07.13D10:01;`MSFT]]; + hclose h; + r2:tp[`open][maindir[];D]; + `REOPENCOUNT set r2 1; + hclose r2 0; + } + +/ open, write one, roll -> the next day's log file must exist +dorollnewfile:{[] + rd:BASE,"/roll"; + r:tp[`open][rd;D]; h:r 0; + tp[`write][h;trademsg[2026.07.13D10:00;`AAPL]]; + r2:tp[`roll][h;rd;D]; + hclose r2 0; + not ()~key hsym`$rd,"/tp",string D+1 + } + +/ build a corrupt log in the given subdir (two good trades, then truncate 8 bytes off +/ the tail so the last message is unreadable). returns the log filename symbol. +buildcorrupt:{[sub] + cd:BASE,"/",sub; + r:tp[`open][cd;D]; h:r 0; + tp[`write][h;trademsg[2026.07.13D10:00;`AAPL]]; + tp[`write][h;trademsg[2026.07.13D10:02;`IBM]]; + hclose h; + fn:hsym`$cd,"/tp",string D; + sz:hcount fn; + fn 1: read1(fn;0;sz-8); + fn + } + +/ open on a corrupt log must fail fast (used by a `fail` test row) +opencorrupt:{[] buildcorrupt["corr"]; tp[`open][BASE,"/corr";D]} + +/ replay must execute the root upd EXACTLY once per recovered message - a naive +/ trap-and-retry would double-process the good messages before the corruption point. +replaynodouble:{[] + fn:buildcorrupt["rep"]; + `CALLS set 0; + old:upd; + `upd set {[t;x] `CALLS set CALLS+1; }; + cnt:tp[`replay] fn; + `upd set old; + cnt=CALLS + } + +/ check on a clean log returns the same file unchanged (the main log has 2 good msgs) +checkcleanok:{[] f:hsym`$maindir[],"/tp",string D; f~tp[`check][f;100]} + +/ replayupto[logfile;n] must replay ONLY the first n messages (subscriber replays exactly +/ the pre-subscription rowcount, not later live-and-logged messages). Writes 4, replays 2. +replayuptopartial:{[] + rd:BASE,"/rep2"; system "mkdir -p ",rd; + r:tp[`open][rd;D]; h:r 0; + tp[`write][h;] each trademsg'[2026.07.13D10:00+(0 1 2 3)*0D00:01;`AAPL`MSFT`IBM`GOOG]; + hclose h; + resetreplayed[]; + cnt:tp[`replayupto][hsym`$rd,"/tp",string D;2]; + (cnt=2) and (2=count replayed) and `AAPL`MSFT~{first (x 1) 1} each replayed + } diff --git a/di/tplogmgr/tplogmgr.md b/di/tplogmgr/tplogmgr.md new file mode 100644 index 00000000..7771bf09 --- /dev/null +++ b/di/tplogmgr/tplogmgr.md @@ -0,0 +1,66 @@ +# di.tplogmgr + +Tickerplant **log lifecycle**: create/open, replay-on-startup, append, and roll. These +pieces do not exist as a module in `kdbx-modules` — `di.tplog` there covers only +corruption *check/repair*, which this module re-exports so consumers have a single +import surface. Ported from the inline log handling in +`TorQ/code/processes/tickerplant.q` (`.u.ld` / `.u.endofday`), which is where classic +TorQ keeps it (its `u.q` is pure pubsub). + +Stateless utility, like `di.tplog` — every function takes its state (dir, date, +handle) as arguments; there is no `init` and no module-local state. + +## The `upd` replay contract + +`open` and `replay` restore state by running `-11!` over the log, which executes the +**root-level `upd`** for each stored `(`upd;t;x)` message. **A caller must define a +root `upd` before calling either.** `di.proc.tickerplant` publishes its `upd` at root during +`init`, before it opens the log; the RDB will do the same before calling `replay`. + +## Functions + +- `logname[dir;date]` — the log filename handle for an absolute-path `dir` string and a + `date`, one file per date: `/tp` (e.g. `` `:/var/tplog/tp2026.07.13 ``). +- `open[dir;date]` → `(handle;count)`. Creates an empty log if absent (count `0`); + otherwise replays it through the root `upd` and returns the message count. Corruption + is detected up front with the **non-executing** `-11!(-2;…)` streaming count, so a + corrupt log is a **fail-fast error** *before* any partial replay mutates state — a + tickerplant must not silently continue on a bad log. +- `write[h;msg]` — append one message (typically `(`upd;t;x)`) to an open handle. +- `roll[h;dir;olddate]` → `(handle;count)`. Closes `h` and opens (creating) the + `olddate+1` log. +- `replay[logfile]` → count. Replays through the root `upd`, **repairing first if + corrupt** (unlike `open`, which fails). Corruption is checked with the non-executing + `-11!(-2;…)` first, so good messages before the corruption point are never replayed + twice — a naive `@[-11!;logfile;{…repair…}]` would partially replay before throwing + and then replay again, double-processing. For consumers (e.g. RDB startup) that should + recover rather than abort. +- `check[logfile;lastmsgtoreplay]` / `repair[logfile]` — re-exported from + `di.tplog`. + +## Dependency + +`di.tplog` (kdbx-modules), called per-invocation via `use` (idempotent, so cheap, +and it sidesteps module-local dependency-variable resolution). No injected DI deps. + +## Known gaps + +- `di.tplog`' message signature is **hardcoded to the `trade` schema** upstream; + `check`/`repair` (and therefore `replay`'s repair path) inherit that limitation until + that module is generalised. `open`'s own corruption *detection* uses `-11!(-2;…)` and + is schema-agnostic; only the *repair* path is trade-specific. +- Filename convention is fixed (`tp`); if multiple logical logs ever need to share + a directory this would need a `logname` prefix parameter. + +## Testing + +`test.csv`/`test.q` (k4unit) cover: fresh open (count 0) + write + reopen-replays-count, +replay restoring state through the root `upd`, roll creating the next day's file, +fail-fast on a corrupt log (`open`), replay repairing a corrupt log while processing +each good message exactly once (the double-processing regression), and `check` returning +a clean log unchanged. Run with: + +```q +q)k4unit:use`di.k4unit +q)k4unit.moduletest`di.tplogmgr +``` diff --git a/di/tplogmgr/tplogmgr.q b/di/tplogmgr/tplogmgr.q new file mode 100644 index 00000000..dc1c3c2a --- /dev/null +++ b/di/tplogmgr/tplogmgr.q @@ -0,0 +1,72 @@ +/ di.tplogmgr - tickerplant log lifecycle: create/open, replay-on-startup, append, roll. +/ These pieces are NOT in kdbx-modules: di.tplog covers only corruption +/ check/repair (which this module re-exports for the replay/RDB side). Ported from the +/ inline log handling in TorQ/code/processes/tickerplant.q (.u.ld / .u.endofday). +/ Stateless utility, like di.tplog - all state (dir, date, handle) is passed in; +/ there is no init and no module-local state to set up. + +/ build the log filename handle for a dir (absolute path string) and date. +/ one file per date: /tp, e.g. :/var/tplog/tp2026.07.13 +logname:{[dir;date] `$":",dir,"/tp",string date} + +/ open (creating if absent) the log for `date` under `dir`. +/ - absent: create an empty log, return (handle;0). +/ - present: replay via -11!, which executes the ROOT-LEVEL `upd` for each stored +/ (`upd;t;x) message, restoring in-memory state; return (handle;replayed-count). +/ A corrupt log is a FAIL-FAST error here - a tickerplant must not silently continue on +/ a bad log. The replay/RDB side uses `replay` (below), which repairs instead. The +/ caller must have a root-level `upd` defined before calling (di.proc.tickerplant publishes +/ one in its init, ahead of opening the log). +open:{[dir;date] + L:logname[dir;date]; + if[not type key L; / log does not exist yet + .[L;();:;()]; / create an empty log file + :(hopen L;0)]; + / -11!(-2;L) streams the log to COUNT messages WITHOUT executing upd - so a corrupt + / log is detected before any partial replay mutates state. Returns a single count for + / a clean log, or (good-count;bytes-read) for a corrupt one. + info:-11!(-2;L); + if[1=good-count replays the whole (repaired) log. +replayupto:{[logfile;n] + info:-11!(-2;logfile); + good:$[1 version strings -true,0,0,q,expdeps~(tml.parsetoml fdeps)`dependencies,1,1,a deps.toml [dependencies] table parses to the symbol!version-string dict di.depcheck readdeps expects +comment,,,,,,,di.torq.depcheck deps.toml contract - [dependencies] table of quoted dotted keys -> version strings +true,0,0,q,expdeps~(tml.parsetoml fdeps)`dependencies,1,1,a deps.toml [dependencies] table parses to the symbol!version-string dict di.torq.depcheck readdeps expects true,0,0,q,11h=type key (tml.parsetoml fdeps)`dependencies,1,1,dependency names are symbols (quoted dotted keys unquoted) true,0,0,q,all 10h=type each value (tml.parsetoml fdeps)`dependencies,1,1,version values stay strings (policy-free) for meetsmin comparison comment,,,,,,,getapimeta diff --git a/di/toml/test.q b/di/util/toml/test.q similarity index 86% rename from di/toml/test.q rename to di/util/toml/test.q index 2fcf18b3..ef8254e9 100644 --- a/di/toml/test.q +++ b/di/util/toml/test.q @@ -1,4 +1,4 @@ -/ di.toml test fixtures (loaded by test.csv). di.toml is pure - no mocks needed; the TOML text is +/ di.util.toml test fixtures (loaded by test.csv). di.util.toml is pure - no mocks needed; the TOML text is / defined here as q string literals (far cleaner than CSV-escaping all the quotes inline) plus a / small temp .toml file fixture for parsefile. @@ -22,8 +22,8 @@ expescarr:("x\"y";"zz"); / expected: two elements x"y and zz fqsec:"[\"a.b\"]\nx = 1"; / TOML ["a.b"] - a QUOTED section name (dot is literal) ftab:"s = \"x\ty\""; / TOML s = "xy" (a literal tab inside the string) exptab:"x\ty"; / expected: x, tab, y - the tab preserved, not spaced -fdeps:"# peer deps\n[dependencies]\n\"di.servers\" = \"0.3.0\" # injected\n\"di.dbwrite\" = \"0.1.0\""; / a di.depcheck deps.toml -expdeps:`di.servers`di.dbwrite!("0.3.0";"0.1.0"); / di.depcheck's readdeps expects [dependencies] -> symbol!version-string +fdeps:"# peer deps\n[dependencies]\n\"di.servers\" = \"0.3.0\" # injected\n\"di.dbwrite\" = \"0.1.0\""; / a di.torq.depcheck deps.toml +expdeps:`di.servers`di.dbwrite!("0.3.0";"0.1.0"); / di.torq.depcheck's readdeps expects [dependencies] -> symbol!version-string TDIR:"/tmp/ditomltest"; setuptoml:{[] system "mkdir -p ",TDIR; (`$":",TDIR,"/x.toml") 0: ("dir = \":appdb\"";"rows = 100");}; diff --git a/di/toml/toml.md b/di/util/toml/toml.md similarity index 80% rename from di/toml/toml.md rename to di/util/toml/toml.md index 176e0e51..2e537954 100644 --- a/di/toml/toml.md +++ b/di/util/toml/toml.md @@ -1,19 +1,19 @@ -# di.toml +# di.util.toml A small, scoped-down TOML parser for the modular TorQ world. It reads settings `.toml` files (and -in-memory TOML text) into q dicts. Its reason for existing is to back di.config's `.toml` -resolution tier — di.config lazily loads di.toml only when a `.toml` file is actually parsed. +in-memory TOML text) into q dicts. Its reason for existing is to back di.torq.config's `.toml` +resolution tier — di.torq.config lazily loads di.util.toml only when a `.toml` file is actually parsed. -**Pure module** — no `init`, no logger, no injected dependencies. di.config invokes it *during +**Pure module** — no `init`, no logger, no injected dependencies. di.torq.config invokes it *during config resolution*, before any logger exists, so parse errors are **signalled** with a clear -`'di.toml: …'` message rather than logged. +`'di.util.toml: …'` message rather than logged. **Fail-loud** — because this is a *shared* utility (any module that parses a file may use it), -di.toml never silently returns nulls or garbage for input it can't correctly handle: a missing +di.util.toml never silently returns nulls or garbage for input it can't correctly handle: a missing file, an unparseable value (bare word / datetime), a dotted key, or a malformed/array-of-tables section header all **signal**. A caller that treats a *missing file* as acceptable (a config -cascade probing optional tiers) must **guard existence itself** before calling — the way di.config -does (`if[0=count key hsym`$path; :()!()]`) — di.toml does not paper over it. +cascade probing optional tiers) must **guard existence itself** before calling — the way di.torq.config +does (`if[0=count key hsym`$path; :()!()]`) — di.util.toml does not paper over it. ## Scope (v1) @@ -35,7 +35,7 @@ array-of-tables (`[[x]]`). - **Strings are policy-free.** TOML has no symbol type, so every TOML string parses to a q **char string** (`10h`), never a symbol. Callers that want a symbol coerce at the point of use (`` `$ `` is a no-op on an already-a-symbol value, so the same consumer code works for `.q` settings too). - This is the contract di.config and its consumers rely on. + This is the contract di.torq.config and its consumers rely on. - **Integers parse to `long`** (matching what `value` gives a `.q` settings line like `rows:100`), floats to `float`, `true`/`false` to `boolean`. @@ -44,20 +44,20 @@ array-of-tables (`[[x]]`). | Function | Signature | Description | |---|---|---| | `parsetoml` | `parsetoml[text]` | Parse a TOML string into a dict (one level of `[section]` nesting). Blank and comment-only lines contribute nothing. | -| `parsefile` | `parsefile[path]` | Read and parse a `.toml` file into a dict. A **missing file signals** — a caller that treats missing as acceptable (a config cascade) guards existence itself first (as di.config does). | +| `parsefile` | `parsefile[path]` | Read and parse a `.toml` file into a dict. A **missing file signals** — a caller that treats missing as acceptable (a config cascade) guards existence itself first (as di.torq.config does). | | `getapimeta` | `getapimeta[]` | This module's api metadata — one row per **callable** function (`parsetoml`, `parsefile`); `getapimeta` itself is plumbing and is deliberately not listed. For `di.torq` to register with `di.api`. | Export is conservative — the internal helpers (`trimstr`, `isquoted`, `instrmask`, `firstunquoted`, `stripcomment`, `splitassign`, `unquotekey`, `parsekey`, `unescape`, `parsescalar`, `splitcommas`, `parsevalue`, `sectname`, `addkv`, `addline`) are not exported. No `version` export / `VERSION` file yet — deferred -to the di.depcheck rollout, as in di.config/di.servers. +to the di.torq.depcheck rollout, as in di.torq.config/di.servers. -## di.config integration contract +## di.torq.config integration contract -di.config's `parsefile` delegates a `.toml` path via `` (use`di.toml)[`parsefile] path ``, expecting +di.torq.config's `parsefile` delegates a `.toml` path via `` (use`di.util.toml)[`parsefile] path ``, expecting a **flat dict** of `setting → value` back (section values are sub-dicts). This module satisfies that -directly. Once di.toml is on `QPATH` alongside di.config, the `.toml` half of di.config's cascade -(and `.toml > .q` within a tier) works, and di.config's guard-rail error (`the di.toml module was +directly. Once di.util.toml is on `QPATH` alongside di.torq.config, the `.toml` half of di.torq.config's cascade +(and `.toml > .q` within a tier) works, and di.torq.config's guard-rail error (`the di.util.toml module was not found on QPATH`) no longer fires. ## Out-of-scope constructs are rejected, not mis-parsed @@ -80,8 +80,8 @@ wrong data: - a non-char input, or a 1-char input (a char atom) — handled/validated at the `parsetoml` entry so it never surfaces as a cryptic `'type` -This is what makes di.toml safe as a shared parser — a consumer feeding a richer or malformed file -gets a clear `'di.toml: …'` error, not quiet garbage. +This is what makes di.util.toml safe as a shared parser — a consumer feeding a richer or malformed file +gets a clear `'di.util.toml: …'` error, not quiet garbage. ## Known limitations @@ -94,7 +94,7 @@ it (and add tests) if a real settings file needs more. ```q k4unit:use`di.k4unit -k4unit.moduletest`di.toml +k4unit.moduletest`di.util.toml ``` `test.csv` (+ `test.q` fixtures) covers scalars and their types, policy-free strings, quoted keys, diff --git a/di/toml/toml.q b/di/util/toml/toml.q similarity index 77% rename from di/toml/toml.q rename to di/util/toml/toml.q index e8a096b7..f59e8443 100644 --- a/di/toml/toml.q +++ b/di/util/toml/toml.q @@ -2,11 +2,11 @@ / q dict. supports: key=value (bare or "quoted" keys), quote-aware # comments, one level of [section] / nesting, and scalars (quoted strings, integer->long, float, true/false, flat arrays). not supported: / inline tables, dotted keys, single-quoted/multi-line strings, datetimes, array-of-tables. -/ fail-loud: anything it cannot correctly parse signals 'di.toml: ...', never silent garbage. +/ fail-loud: anything it cannot correctly parse signals 'di.util.toml: ...', never silent garbage. / strings parse to q char strings, never symbols (TOML has none) - callers coerce with `$ at use. -/ pure: no init/logger/deps - di.config loads it during config resolution, before a logger exists. +/ pure: no init/logger/deps - di.torq.config loads it during config resolution, before a logger exists. / parsefile signals on a MISSING file; a caller for whom that is acceptable (a cascade probing -/ optional tiers) guards existence itself first, as di.config does: if[0=count key hsym`$path;:()!()]. +/ optional tiers) guards existence itself first, as di.torq.config does: if[0=count key hsym`$path;:()!()]. / reserved-word trap: cut/trim/parse/ss/sv/vs/ssr are builtins - hence trimstr/parsetoml/etc. keychars:.Q.a,.Q.A,.Q.n,"_-"; / chars allowed in a bare key; anything else must be "quoted" @@ -20,10 +20,10 @@ parsekey:{[raw] / validate + resolve a bare-or-"quoted" key OR section name to a symbol - both follow the same / rule. a bare name is A-Za-z0-9_- only; a "quoted" name takes any chars (a "." is then literal). / empty, dotted-bare (nesting, out of scope), and invalid-bare names all signal. - if[0=count raw;'"di.toml: empty key or section name"]; + if[0=count raw;'"di.util.toml: empty key or section name"]; if[not isquoted raw; - if["." in raw;'"di.toml: dotted keys/sections are not supported (quote the name if the . is literal): ",raw]; - if[not all raw in keychars;'"di.toml: invalid bare name (only A-Za-z0-9_- allowed; quote otherwise): ",raw]]; + if["." in raw;'"di.util.toml: dotted keys/sections are not supported (quote the name if the . is literal): ",raw]; + if[not all raw in keychars;'"di.util.toml: invalid bare name (only A-Za-z0-9_- allowed; quote otherwise): ",raw]]; `$unquotekey raw}; sectname:{[hdr] parsekey trimstr hdr 1+til -2+count hdr}; @@ -43,7 +43,7 @@ firstunquoted:{[c;s] splitassign:{[l] / (key;value) split on the first unquoted "=" ; a line with no "=" is malformed. - if[count[l]=eq:firstunquoted["=";l];'"di.toml: not a key = value line: ",l]; + if[count[l]=eq:firstunquoted["=";l];'"di.util.toml: not a key = value line: ",l]; trimstr each 0 1_'(0,eq)_l}; unescape:{[s] @@ -51,10 +51,10 @@ unescape:{[s] / single pass (not an ordered ssr-chain) is needed so a \\ next to an escape char resolves right. m:"\"nt\\"!"\"\n\t\\"; r:{[m;a;c] - $[a 1;[if[not c in key m;'"di.toml: invalid string escape: \\",c];(a[0],m c;0b)]; + $[a 1;[if[not c in key m;'"di.util.toml: invalid string escape: \\",c];(a[0],m c;0b)]; c="\\";(a 0;1b); (a[0],c;0b)]}[m]/[("";0b);s]; - if[r 1;'"di.toml: dangling backslash in string"]; + if[r 1;'"di.util.toml: dangling backslash in string"]; r 0}; parsescalar:{[tok] @@ -65,7 +65,7 @@ parsescalar:{[tok] if[tok~"true"; :1b]; if[tok~"false";:0b]; if[null v:$[any tok in ".eE";"F"$tok;"J"$tok]; - '"di.toml: unparseable value (quote strings; bare words/datetimes are out of scope): ",tok]; + '"di.util.toml: unparseable value (quote strings; bare words/datetimes are out of scope): ",tok]; v}; splitcommas:{[s] @@ -77,9 +77,9 @@ parsevalue:{[v] / a "[ ... ]" array -> list of scalars (empty -> ()); else a single scalar. empty and unterminated / values are rejected. v:trimstr v; - if[0=count v;'"di.toml: missing value"]; + if[0=count v;'"di.util.toml: missing value"]; if["["=first v; - if[not "]"=last v;'"di.toml: malformed array (must be [ ... ]): ",v]; + if[not "]"=last v;'"di.util.toml: malformed array (must be [ ... ]): ",v]; inner:trimstr 1_-1_v; :$[0=count inner;();parsescalar each splitcommas inner]]; parsescalar v}; @@ -87,7 +87,7 @@ parsevalue:{[v] addkv:{[d;k;v] / add k->v, signalling on a duplicate (a repeated key/section, or a key/section clash - TOML errors). / catenation (not ,:) keeps the value list general so mixed value types never hit a type-widen error. - if[k in key d;'"di.toml: duplicate key: ",string k]; + if[k in key d;'"di.util.toml: duplicate key: ",string k]; d,(enlist k)!enlist v}; addline:{[acc;line] @@ -96,8 +96,8 @@ addline:{[acc;line] top:acc 0; cursect:acc 1; sect:acc 2; $[(first line)="["; [hdr:trimstr line; - if[not "]"=last hdr;'"di.toml: malformed section header (missing ]): ",line]; - if["[["~2 sublist hdr;'"di.toml: array-of-tables [[...]] is not supported: ",line]; + if[not "]"=last hdr;'"di.util.toml: malformed section header (missing ]): ",line]; + if["[["~2 sublist hdr;'"di.util.toml: array-of-tables [[...]] is not supported: ",line]; nm:sectname hdr; if[not null cursect;top:addkv[top;cursect;sect]]; (top;nm;()!())]; @@ -109,15 +109,15 @@ addline:{[acc;line] parsetoml:{[text] / TOML text -> dict (one level of [section] nesting). accepts a string (or the char atom q makes of / a 1-char literal); other types signal - else a 1-char input is an atom and ssr/vs throw 'type. - if[not 10h=abs type text;'"di.toml: parsetoml expects a char string; got type ",string type text]; + if[not 10h=abs type text;'"di.util.toml: parsetoml expects a char string; got type ",string type text]; lines:trimstr each stripcomment each "\n" vs $[10h=type text;text;enlist text]; acc:addline/[(()!();`;()!());lines where 0 Method note for the remaining re-syncs: always diff against the vendoring **source commit** to +> isolate local patches, and source-commit→tip to isolate drift. Diffing only against the tip +> conflates the two — that conflation is what put a phantom "eodtime patched (`di.tz`)" row into the +> RFC matrix. + +## The win: the monadic log bridge is gone + +Upstream moved dbwrite to the **binary** `` `info`warn`error `` `{[c;m]}` contract +([dbwrite.q:21-25](../../di/dbwrite/dbwrite.q#L21-L25), *"no adaptation here, so a monadic kx.log +instance must be wrapped first"*). That is exactly what di.torq injects, so the adapter both write +processes carried is now dead weight and has been **removed**: + +- `di/proc/rdb/rdb.q` — deleted `monadiclog` (folded a fixed `` `rdb `` context into each message) + and its explanatory comment; the init call is now + `` (.z.m.dbw`init)[enlist[`log]!enlist deps`log] ``, passing the injected dep straight through. +- `di/proc/wdb/wdb.q` — same, with the `` `wdb `` context. +- `rdb.md` / `wdb.md` — the paragraphs describing the bridge rewritten to say no adapter is needed, + noting why it used to exist. + +## Changes applied + +Placed at `di/dbwrite` (flat — vendored/upstream-canonical modules keep their upstream names until +the RFC phase-5 rename), byte-identical to `main` except: + +- **`VERSION` (0.1.0)** and a **`version` export** — both required, not cosmetic: *two* consumer + manifests declare it (`di/proc/rdb/deps.toml`, `di/proc/wdb/deps.toml`, each + `"di.dbwrite" = "0.1.0"`), and di.torq runs both depcheck phases every startup — the pre-load + walk reads the file, the post-load audit reads the export. Safe to export here: no `getapimeta` + and no test asserting an exact export set. + +## Verification + +- **`di.dbwrite` k4unit: 166/166 green.** +- **`di.proc.rdb` 4/4 and `di.proc.wdb` 4/4 still green** after the bridge removal. +- Full 18-module regression: **1114 checks, 0 failures.** + +## Note on consumer coverage (pre-existing gap) + +`di.proc.rdb`, `di.proc.wdb` and `di.proc.gateway` each have only a 9-line `test.csv` — 4 real +checks apiece, covering init-validation errors and the export set, nothing behavioural. So the +bridge removal is verified by "init still succeeds and the module still loads", not by an +exercised savedown. `di.proc.hdb` (19) and `di.proc.tickerplant` (30, with a real `test.q`) are the +only proc modules with substantive suites. Worth its own piece of work. diff --git a/docs/reconciliation/depcheck.md b/docs/reconciliation/depcheck.md new file mode 100644 index 00000000..77581396 --- /dev/null +++ b/docs/reconciliation/depcheck.md @@ -0,0 +1,77 @@ +# Reconciliation — `depcheck` → `di.torq.depcheck` (merge) + +**Status:** module reconciled + verified (120 k4unit checks). Both the pre-load graph AND the +post-load `init` audit are wired into di.torq. End-to-end verification awaits `servers` (di.torq is +inert until then). +**Decision:** **merge** (your call) — kdbx `feature-depcheck` canonical, + TorqX's pre-load VERSION graph. +**Sides:** kdbx `origin/feature-depcheck:di/depcheck` · TorqX `di/torq/depcheck` + +## The fork + +The two took fundamentally different approaches: + +- **kdbx `feature-depcheck` — post-load session audit.** Runs via `init[deps]` *after* di.torq has + `use`d everything, introspecting the loaded modules' namespaces — never calls `use` itself. More + polished: reads **both `deps.q` and `deps.toml`** (merged), robust semver (malformed-version + sentinel, non-string-minver detection), **introspection-based** contract checks, a kdb-x + **engine-version check** (`.z.K`), and careful malformed-manifest handling. Its one acknowledged + limitation: it **can't version-check unloaded modules transitively** ("deferred until a per-module + VERSION-file rollout"). +- **TorqX `di.torq.depcheck` — pre-load filesystem check.** Runs at the *start* of di.torq.init + (before any load), resolving modules on QPATH and reading **VERSION files** — catching version + mismatches *before* the `use` avalanche, transitively. The "customer bumped gateway but not + serverselect → clean startup error" scenario. + +They're complementary: TorqX's on-disk VERSION-file walk is exactly what lifts kdbx's deferred +limitation, now that the VERSION-file rollout is happening. + +## What was done + +**Canonical = kdbx feature-depcheck**, placed at `di/torq/depcheck`, `di.depcheck`→`di.torq.depcheck`, +`di.toml`→`di.util.toml`, VERSION file + `version` read in init.q. + +**Hierarchy adaptation (necessary — kdbx assumed flat names).** kdbx introspects the session +namespace assuming `di.x` → `.m.di.0x`. Our framework modules are nested (`di.torq.handlers` → +`.m.di.0torq.0handlers`). Generalised: +- `modparentns`/`modns`/`nspathtomod` — map an arbitrarily-nested module name to/from its namespace + (replacing the flat `modvendorns`/`shorttofull`). +- `loadedmodules[]` — recursively enumerate every loaded di.* module by full dotted name (a node is + a module iff it has an `export` key; it may also parent children — di.torq is both). Replaces the + flat `key .m.di` walk in `checkdeps`/`checkgraph`. +- `checkmoduledeps` now takes a full dotted name (a nested name can't be rebuilt from a bare `0x`). +- `contracts` dict updated to the reconciled provider names (`di.util.log`/`di.timer`/`di.torq.handlers`). + +**Grafted TorqX's pre-load VERSION graph** (reusing kdbx's `resolvemodule`/`readdeps`/`vergte` + +a new on-disk `readversion`): `checkinstalledversion`, `visitversion`, **`checkversiongraph`** +(from module entries), **`checkversiongraphfile`** (from an app/custom manifest file). Exported. +Pure on-disk reads — safe at the very start of init. + +**Wired into di.torq (pre-load):** replaced the old `check`/`checkgraph`/`checkgraphfrom`/ +`checkztsintegrity` calls with `checkversiongraphfile` (app deps.toml) + `checkversiongraph` +(built-in proctype entry) / `checkversiongraphfile` (custom process manifest), still before any load. + +**Verified: 117 k4unit checks green** — kdbx's full audit (hierarchy-adapted) + 21 new pre-load +version-graph tests (readversion, checkinstalledversion pass/below-min/not-found, transitive +`checkversiongraph` attributing a depth-2 fault, `checkversiongraphfile` pass/fail/absent). + +## Post-load `init` audit into di.torq — DONE (`cp` contract aligned) + +kdbx's `init` (checkdeps + checkgraph + checkcontracts + ztscheck + kdbxcheck) is a valuable +post-load audit. Wiring it as a *fatal* startup audit hit one snag: the `contracts` dict required +**`cp`** on `di.timer`, which the real `di.timer` exports as `setcp` — so `checkcontracts[]` would +always report "di.timer missing cp" and `init` would raise on **every** startup. + +**Resolution (chosen): aligned the timer contract** — dropped `cp` down to the five keys di.torq's +own `buildtimerdep` actually uses (`addjob`/`deletejobs`/`enablejobs`/`disablejobs`/`getactivejobs`). +`checkcontract` stays generic, so a caller can still audit `cp` explicitly. Updated the two tests +built on the old gap: the standalone `checkcontracts[]` assertion now checks di.timer *satisfies* +its contract, and the end-to-end "init throws" test drives its failure from a fabricated loaded +module whose on-disk `deps.q` requires an absent module (a real `checkdeps` failure) instead. + +**Wired:** `(dc\`init)[\`log\`minkdbxversion!(logdep; config\`minkdbxversion or 0Nf)]` runs after +`loadappcode` (every module loaded), so it audits the live session — contract shapes, `.z.ts` +ownership (kdbx's `ztscheck`, which replaces TorqX's old pre-load `checkztsintegrity`), and an +optional engine-version minimum. Raises on a real contract/dependency gap. + +Both di.torq and di.torq.depcheck load clean. End-to-end verification (the audit running in a real +booting stack) awaits the `servers` reconciliation, after which di.torq's own suite goes green. diff --git a/docs/reconciliation/eodtime.md b/docs/reconciliation/eodtime.md new file mode 100644 index 00000000..836a1e42 --- /dev/null +++ b/docs/reconciliation/eodtime.md @@ -0,0 +1,60 @@ +# Reconciliation — `eodtime` (stays flat: `di.eodtime`) + +**Status:** LANDED + verified (49 k4unit green — the 3 long-standing kx.log-env failures are gone). +**Decision:** canonical = **kdbx `main`** (merged 2026-08-05 as **#108**). A **re-sync**; we never +patched it. +**Sides:** kdbx `origin/main:di/eodtime` · TorqX `di/eodtime` (vendored at `5f09606`, 2026-06-25) + +## Correcting the record: there was never a `di.tz` patch + +The RFC appendix listed this module as *"vendored + **patched** (`di.tz`) → PR the fix back"*. That +is **empirically false**. The vendored base commit `5f09606` already had `` tz:use`di.tz ``, as do +main's tip and our copy — the three agree, so there is nothing to feed back. The `di.tz` +vs `di.timezone` business was **cross-branch naming churn**, not an eodtime code change: main +renamed timezone→tz in #91, while `feature-serverselect` and `feature/dbwritemodule` are still based +on pre-rename main and carry the old names. Our copy pointed at the main-side name, which was a +*choice about which checkout we ran against*, never a patch. + +Likewise, the `normlog` helper in our copy (which auto-normalised a monadic kx.log instance) was +**not ours** — it was upstream code, added in `bb637de` and **removed** upstream in `bb9f1a2`. We +were simply holding a snapshot that still contained it. + +## What we gain by re-syncing + +Three commits of upstream work we were missing: + +- **A real DST fix.** Upstream extracted `rolltod` and changed `getroll` to recompute the roll + offset for **tomorrow** when today's roll time has passed + (`$[z<=p;("d"$p+1D)+rolltod[p+1D];("d"$p)+z]`) instead of just adding `1D` to today's offset. + That matters across a DST transition, and upstream ships the test for it (Europe/London clocks + going back on 2025.10.26). +- The newer logging format, and an `init` that requires **at minimum** an `` `info `` key rather + than all three levels. +- The test suite that replaced our copy's three kx.log-environment failures. + +## Contract check — no consumer change needed + +`init` wants `deps`log` as a binary `{[c;m]}` dict with at least `` `info `` +([eodtime.q:78](../../di/eodtime/eodtime.q#L78)) — exactly what di.torq injects. +`di.proc.tickerplant`'s `eoddeps` builds `` `log ``→logdep plus optional tz config and passes it +straight in, so it works unchanged. + +## Changes applied + +Placed at `di/eodtime` (flat — vendored/upstream-canonical names hold until the RFC phase-5 +rename), byte-identical to `main` except: + +- **`VERSION` (0.1.0)** and a **`version` export** — required, because + `di/proc/tickerplant/deps.toml` declares `"di.eodtime" = "0.1.0"` and di.torq runs both depcheck + phases (pre-load reads the file, post-load reads the export). Safe: no `getapimeta`, no + exact-export-set assertion. +- Deliberately **no `deps.toml`** for the module itself. It `use`s `di.tz`, which ships no `VERSION` + file, so declaring that peer would make depcheck's "has no VERSION file" branch fail a live + tickerplant. A manifest-less module is a safe leaf — the walk stops there. (Adding a VERSION file + to `di.tz` is the clean fix, and is a separate upstream change.) + +## Verification + +- **`di.eodtime` k4unit: 49/49 green** (our stale copy had 3 failures). +- **`di.proc.tickerplant` 30/30 green** against the re-synced module, unchanged. +- Full 18-module regression: **1114 checks, 0 failures.** diff --git a/docs/reconciliation/handlers.md b/docs/reconciliation/handlers.md new file mode 100644 index 00000000..9956b208 --- /dev/null +++ b/docs/reconciliation/handlers.md @@ -0,0 +1,87 @@ +# Reconciliation — `handlers` → `di.torq.handlers` + +**Status:** RECOMMENDED (landed in working tree; feed the `transform` addition back to `feature-handlers`) +**Decision:** canonical = **kdbx `feature-handlers` implementation** (a clean superset), placed at +`di/torq/handlers`. TorqX's `di.torq.handlers` retired, **except** its result-transforming +capability, which is carried across as a new `transform` phase (below). +**Sides:** kdbx `origin/feature-handlers:di/handlers` · TorqX `di/torq/handlers` (was `di.zed`) + +## Capability comparison + +The `feature-handlers` author adopted TorqX's two-kind model (simple fan-out events vs phased +`pre → exec → post` around one owner) and extended it substantially. It is a superset: + +| Capability | TorqX | kdbx `feature-handlers` | +|---|---|---| +| Events | 4 (`pc po`, `ps pg`) | **12** (`pc po exit wo wc`; `pg ps pi pp ph ws pw`) | +| Pre-existing/default `.z.*` handler | warns + overwrites | **captures, runs last, restores on remove** | +| Arg type validation | none | full | +| Exec ownership | one exec | explicit **owner** model + ordering rule | +| Auth/HTTP specials | none | `.z.pw` (redacted post), `.z.ph` default-restore | +| **`post` semantics** | **chained, can transform result** | **observe-only (owner owns the result)** | + +kdbx's capture-and-restore behaviour is a genuine improvement — it also fixes the `di.pubsub` +sets-its-own-`.z.pc` coexistence gap (pubsub's handler is captured and still fires). + +**Usage check (why the divergence is safe to reconcile):** across all of TorqX, only *simple* +events are used — `di.torq.servers` registers `.z.pc`, `di.proc.gateway` registers `.z.po`+`.z.pc`. +No consumer used phased events, post-transform, or exec-default. So adopting kdbx's model breaks +nothing we built. + +## The one capability we preserve: result-transforming `post` + +TorqX's `post` could **rewrite the outgoing result** (`{[acc;f] f acc}/[res;posts]`). kdbx made +`post` observe-only on purpose ("the exec owner owns the result"). Rather than reverting that +deliberate choice, we **split the two concerns** and added a distinct **`transform`** phase: + + pre (transform request) → exec (owner produces result) → transform (rewrite result, chained) → post (observe final) + +- `transform` handlers are `{[result] …}`, priority-ordered, chained, unprotected (same shape as + `pre`, but on the result side). Multiple allowed. Require an exec owner first (same rule as + pre/post). Cleared when the exec owner is removed. +- kdbx's `pre`/`exec`/`post` semantics are **unchanged** — all upstream tests still pass. This + keeps the addition a self-contained, cherry-pickable block. + +**Rationale for a distinct phase (not overloading `post`):** an application decorating a query +result (serialisation, redaction, envelope-wrapping) wants to *rewrite* the result; a metrics/audit +watcher wants to *observe* the final result. Conflating them (TorqX's original `post`) means an +observer accidentally returning a value silently mutates the outgoing result. Separate phases make +the intent explicit and let both coexist. + +Not ported (deliberately): TorqX's "exec defaults to `value`, pre/post without an exec owner". +kdbx's mandatory-owner model is sound and nothing depends on the default; left as-is. + +## Changes applied on placement + +- Placed at `di/torq/handlers`; `di.handlers` → `di.torq.handlers` throughout (error prefixes, + docs, tests). Internal mangled namespace is `.m.di.0torq.0handlers` (test assertions updated). +- Added a `VERSION` file and read `version` from it in `init.q` (the author noted no version / + depcheck convention existed; there is one — `di.depcheck` reads VERSION from disk). +- Added the `transform` phase (dispatch, register/remove routing, install, list, teardown, init, + validation) + a `transform` test block. +- **Event-name convention:** the canonical module uses full `.z.*` symbols. Updated the placed + consumer `di.proc.gateway` (`` `po ``→`` `.z.po ``, `` `pc ``→`` `.z.pc ``). **Note for the + `servers` reconciliation:** `di.torq.servers` registers `` `pc `` and will need the same + `` `.z.pc `` update when it lands. +- Simplified `di.torq`'s `buildhandlersdep` — the canonical module exports the contract names + (`register`/`remove`/`list`) directly, so the old `deregister`→`remove` alias is gone. +- Verified: **160 k4unit checks green** including the full `transform` block. (The separate + spawn-based `test_integration.csv` exercises the simple `.z.pc` path, untouched by this change.) + +## PR feedback for the author (ready to paste on the feature-handlers PR) + +> The TorqX consolidation adopted this module as canonical — it's a clean superset of our version +> (broader event coverage, the capture/restore of pre-existing handlers, the ownership model, the +> `.z.pw`/`.z.ph` specials). Thank you. One capability from our version we'd like to fold back: +> **a `transform` phase** for phased events. +> +> Our apps use phased handlers to *rewrite* the outgoing result (serialise/redact/wrap a `.z.pg` +> response), which your observe-only `post` intentionally doesn't allow. Rather than change `post`, +> we added a distinct `transform` phase that threads the result through a chained +> `{[result] …}` between `exec` and `post`: `pre → exec → transform → post`. It reuses your +> satellite-table machinery (priority-ordered, requires an exec owner, cleared on owner removal), +> leaves `pre`/`exec`/`post` untouched (all your tests pass), and adds a `transform` test block. +> The diff touches `dispatchphased`/`dispatchpw`, `installphased`, `registerprepost`/`removeprepost` +> (now pre/transform/post), `removeexec`, `phasedlist`, `init`, and the `register`/`remove` phase +> validation. Happy to open it as a PR against your branch — flagging here first so the design (a +> separate phase vs overloading `post`) is yours to weigh in on. diff --git a/docs/reconciliation/log.md b/docs/reconciliation/log.md new file mode 100644 index 00000000..226dd6ac --- /dev/null +++ b/docs/reconciliation/log.md @@ -0,0 +1,95 @@ +# Reconciliation — `log` → `di.util.log` + +**Status:** LANDED + verified (119 k4unit green; full framework regression green). +**Decision:** canonical = **kdbx `main`'s `di/log`** (PR #90). Our interim stub is **retired**. +**Sides:** kdbx `origin/main:di/log` · TorqX `di/util/log` (stub) + +> **Supersedes the first pass (2026-08-04).** That pass concluded there was *no competing +> implementation*: `origin/feature-logging` was an empty placeholder and no `di/log` existed on any +> branch, so TorqX's stub was placed as-is with the real implementation left as a future sprint. +> That is no longer true — **PR #90 landed a real structured logger on `main` on 2026-08-05**, +> alongside four other merges (toml #116, eodtime #108, config #113, dbwrite #95). This record +> replaces the earlier one; the follow-up it described ("real implementation, its own sprint") is +> now **done upstream**, not outstanding. + +## Why main's implementation wins + +No contest — ours was explicitly an interim stub (`.z.p LEVEL ctx msg` to stdout/stderr, three +functions, 8 lines) whose own header said "real `di.util.log` wraps kx.log; swap later". Main's is +the real thing: + +- **`createlog[]` factory** returning independent logger instances: six levels + (`trace debug info warn error fatal`) with level filtering, multiple named format templates + (`basic`/`syslog`/`raw`, plus `addfmt` for custom), and add/remove of multiple **sinks** per level + (each a `(handle;sender)` pair, so mixed types never collide). +- **printf-style messages** — `fmtmsg` accepts either a plain string or `(fmtstring;args…)` with + `%s`/`%r`/`%%`, arity-checked against the format string. +- **rfc5424 syslog severities**, os-aware newline, `$p/$l/$i/$h/$m/$s` format substitution. +- **`logdict`** — a ready-made `` `log!(6 levels) `` dict designed to drop straight into any + `di.*` module's `init[deps]`. + +## Drop-in for the injected contract + +The crux: main's module-level `trace/debug/info/warn/error/fatal` are plain `{[ctx;msg]}` binary +functions — **exactly** the contract di.torq injects. `di.torq.buildlogdep` does +`` lg:use modname; `info`warn`error!(lg`info;lg`warn;lg`error) `` ([torq.q:67](../../di/torq/torq.q#L67)), +so it picks up the new module unchanged, and `di.torq.depcheck`'s `contracts` entry for +`di.util.log` (`` `info`warn`error ``) is satisfied — verified live, `checkcontract` returns `()`. + +**No consumer changed.** Not one of the ~20 `di.util.log` reference sites needed an edit. + +## Naming: kept at `di.util.log` (the toml precedent) + +Main ships this flat as `di.log`; we keep the hierarchical `di.util.log` and rename on the way in — +identical treatment to `di.util.toml`, which also now sits flat on main as `di/toml`. Deliberately +*not* the `di.serverselect` treatment (kept flat), because unlike serverselect this name is already +load-bearing across the branch: it is di.torq's **default log module** +(`modname:$[`log in key overrides;overrides`log;`di.util.log]`), a key in depcheck's `contracts` +dict, the subject of a depcheck version assertion, and the referent of a dozen error messages. + +The rename is a safe plain substitution — `di.log` is not a substring of `di.util.log` — applied +with a `(?!\w)` guard so nothing else absorbs it. Only `test.csv` (1 line) and `log.md` (7) carried +the name; `log.q` itself never mentions it. + +> Worth flagging for RFC phase 5: toml, config, log, eodtime and dbwrite are now all **flat on +> main** while this branch carries hierarchical copies of the first three. The flat↔hierarchy +> divergence this creates is exactly what phase 5 exists to resolve, but it is now growing on the +> main side rather than only on ours. + +## Changes applied + +Placed at `di/util/log`, replacing all four stub files with main's, plus: + +- **`VERSION` kept at 0.1.0** — deliberately *not* bumped. Nothing pins it (no `deps.toml` + declares `di.util.log`), the module has never shipped outside this branch, and + [depcheck/test.csv:48](../../di/torq/depcheck/test.csv#L48) asserts the live module reports + `found 0.1.0`. Holding the number keeps that assertion honest at zero churn. +- **`version` export added** to `init.q` — safe here: this module has no `getapimeta` and no test + asserting an exact export set (unlike di.util.toml / di.torq.config / di.torq.servers, where the + contract test forced VERSION-file-only). + +## One behavioural change to note + +Our stub sent `error` to **stderr** (`-2`); main's `logline` sends **every** level to stdout +(`-1`) — confirmed empirically (an error line still appears with `2>/dev/null`). Low impact in +practice: `torqx.sh` redirects both streams to the same per-process log file, and the systemd units +send both to the journal. But it is a real change, and "errors belong on stderr" is worth raising +with the author rather than patching locally. + +## Verification + +- **`di.util.log` k4unit: 119/119 green** (was 4/4 for the stub) — instance isolation, level + filtering, format templates incl. custom, multi-sink add/remove, printf substitution, invalid + level/format rejection. +- **Live probe:** `version` reads `"0.1.0"`; the three injected functions are all binary and emit + the new structured line (`2026.08.06D… [INFO] [myctx] …`); `checkcontract` returns `()`; + `logdict` is `` `log ``→ all six levels. +- **Full framework regression, each in its own process:** toml 60, **log 119**, config 58, + depcheck 120, handlers 160, servers 35, tplogmgr 12, serverselect 129, di.torq 35 — **all green**. + di.torq's 35 are the end-to-end ones, so the whole stack now boots on the real logger. + +## Follow-ups + +- `origin/feature-logging` (still an empty placeholder) can now simply be **closed** — the work it + was reserved for landed as #90. +- Raise the stderr question above with the author. diff --git a/docs/reconciliation/pubsub.md b/docs/reconciliation/pubsub.md new file mode 100644 index 00000000..0fe3c866 --- /dev/null +++ b/docs/reconciliation/pubsub.md @@ -0,0 +1,78 @@ +# Reconciliation — `pubsub` (stays flat: `di.pubsub`) + +**Status:** COMPLETE — our patch is **merged upstream** (`main` **#118**, 2026-08-06) and this branch +is re-synced to it. 96 k4unit green. +**Decision:** canonical = **kdbx `main`**. This was the one vendored module whose canonical home was +already merged, and the one genuine patch we owed upstream. +**Sides:** kdbx `origin/main:di/pubsub` · TorqX `di/pubsub` (vendored + patched) + +## The defect we fixed + +`callendofday` broadcast the end-of-day signal to every subscriber. Before #118: + +```q +callendofday:{(neg getallhandles[])@\:`endofday`}; +``` + +Two independent defects: + +1. **The date was silently discarded.** The lambda has no explicit parameter list and never + references `x`, yet still has **rank 1** — so `callendofday[d]` (which + [tickerplant.q:83](../../di/proc/tickerplant/tickerplant.q#L83) does, after computing the + partition date from eodtime) is accepted and the date thrown away. A subscriber had no way to + learn which partition to save. +2. **The payload was not what it looked like.** Note the **trailing backtick**: `` `endofday` `` is + not a bare symbol but a 2-element symbol *vector* `` (`endofday;`) `` — almost certainly a typo. + +### The mechanism, corrected + +Our own patch comment, and the project notes behind it, said *"a bare async symbol is not applied by +a default `.z.ps` — `value` returns the fn, doesn't call it — so the subscriber's EOD never fired."* +**That is wrong about this code**, and was corrected by direct test before the PR went out. It +describes a *bare* symbol, which is not what was sent. Verified behaviour under the default +`.z.ps` (= `value`): + +| payload | what `value` does | +| --- | --- | +| `` `endofday `` (genuinely bare) | returns the function object, **never calls it** | +| `` `endofday` `` (what was sent) | **calls** `endofday[`]` — fires with the *empty symbol* as its date | +| `` (`endofday;d) `` (the fix) | calls `endofday[d]` with the real date | + +So the stray backtick accidentally turned "never fires" into "fires with a junk argument" — the +worse failure, because it is silent. Concretely, [rdb.q:66](../../di/proc/rdb/rdb.q#L66) +`endofday:{[date] …}` ran with `` date=` ``, logged `"end of day for partition "` (empty, since +`` string ` `` is `""`), and passed that null symbol into `savedown` as the partition. `savefn` +traps and logs its errors, so it failed **quietly into the log** rather than stopping the roll — +which is why this presented as "EOD never happened". + +## What merged + +The author took the fix and **extended it to `callendofperiod`**, which had the identical shape and +which we had never patched: + +```q +callendofday:{[d](neg getallhandles[])@\:(`endofday;d)}; +callendofperiod:{(neg getallhandles[])@\:(`endofperiod;x)}; +``` + +## Changes applied here + +This branch's `di/pubsub` predated #118 and still carried the buggy version, so it was re-synced +byte-identical to `main`, plus: + +- **`VERSION` (0.1.0)** and a **`version` export** — `di/proc/tickerplant/deps.toml` declares + `"di.pubsub" = "0.1.0"`, so depcheck needs the file (pre-load walk) and the export (post-load + audit). Safe: no `getapimeta`, no exact-export-set assertion. + +## Verification + +- **`di.pubsub` k4unit: 96/96 green** on the re-synced module. +- **`di.proc.tickerplant` 30/30 green** — it is the producer that calls `callendofday[d]`. +- Full 18-module regression: **1114 checks, 0 failures.** + +> **This suite is flaky when run back-to-back with other spawn-heavy suites.** A run inside a +> sequential multi-module loop showed 14 failures in the subscription-registry assertions +> (`reqalldict[`quote]` and friends) — none of which even mention EOD. Three consecutive **isolated** +> runs, and a later full-regression pass, were all 96/96. The cause is spawned-child/port +> interference between consecutive q processes, not the module. If this suite reports failures, re-run +> it alone before believing them. diff --git a/docs/reconciliation/servers.md b/docs/reconciliation/servers.md new file mode 100644 index 00000000..c1c2ef3b --- /dev/null +++ b/docs/reconciliation/servers.md @@ -0,0 +1,64 @@ +# Reconciliation — `servers` → `di.torq.servers` + +**Status:** LANDED + verified. **di.torq's full suite is now green** — servers was the last core +dep, so the whole framework tier boots end-to-end. +**Decision:** canonical = **kdbx `feature-server`** (a superset; already injected-style). +**Sides:** kdbx `origin/feature-server:di/servers` · TorqX `di/torq/servers` + +## Why kdbx's implementation wins + +Both are the injected connection-management capability (process.csv phone book, handle-by-type +lookup, a `.z.pc` cleanup observer + a retry timer job, idempotent init). kdbx's is the more +complete and polished: + +- **Already injected-style and already correct on the handlers contract** — its init registers + `(handlers[\`register])[\`.z.pc;\`;\`servers;0j;pcfunc]`, i.e. the **full `.z.pc`** event name and + the `register[event;phase;nm;pri;func]` shape the reconciled `di.torq.handlers` expects. So the + `` `pc ``→`` `.z.pc `` fix flagged during the handlers step is **already done** here. +- `raiseerror` (log-then-signal), `getapimeta` (di.api), a `cleanup` sweep for handles that vanish + *without* a clean `.z.pc` (ungraceful peer death), the catenate-not-`insert` module-local-rewrite + note, the "10s not 10000ms" retry-period typo guard, and careful `hopen (h;timeout)` rank notes. +- A real spawned-peer integration test (a genuinely separate licensed q) exercising connect / + gethandle / ungraceful-kill → cleanup → retry-reconnect / waitfortype. + +## The one integration change: `startup` takes the config + +kdbx uses the one-arg `init[deps]` convention (config merged into deps), matching how di.torq +already calls handlers/config/depcheck — good. But its `startup[]` was **no-arg**, reading +connections from init-time config. That doesn't fit the consumer pattern: each consumer computes a +**role-specific** connection list (an rdb dials its tickerplant+hdb types, a gateway its backend +types) and passes it at startup — di.torq can't know that list at init time. + +So `startup` now takes the **config** (reading `connections` + `processcsv` from it), keeping all of +kdbx's internals. This exactly matches the consumers' existing `(\`servers\`startup)[sconfig]` calls, +so **the consumers (rdb/wdb/gateway) need no changes**. `init` still handles self-identity + the +one-time `.z.pc`/retry registration; `startup` handles the (per-consumer) connections. + +## Changes applied + +- Placed at `di/torq/servers`; `di.servers`→`di.torq.servers`, `di.handlers`→`di.torq.handlers`, + `di.log`→`di.util.log`; `VERSION` file (0.3.0), no `version` export (would break the `getapimeta` + contract test — same call as toml/config/depcheck/servers). +- `startup[]` → `startup[config]`; `getapimeta`'s `startup` row updated to match. +- **di.torq wiring:** `buildserversdep` now merges config + injectables into a one-arg `init[deps]`; + di.torq stashes the `process.csv` path into `config` (`processcsv`) after the identity stamp, so + both servers.init and each consumer's `sconfig` carry it (keeps servers' env-free boundary). +- **Test harness fix:** the kdbx test loaded its fixtures via `di.os.abspath`, whose GNU + `realpath -ms` fails on macOS, and still used the old flat `di/servers/test.q` path. Switched to + the cwd-relative `system "l di/torq/servers/test.q"` (moduletest guarantees cwd=repo root) — same + pattern as every other module test; dropped the `di.os` dependency. + +## Verification + +- **`di.torq.servers` k4unit: 35/35 green** (real spawned-peer integration). +- **`di.torq` k4unit: 35/35 green** — the payoff. With servers landed, di.torq boots end-to-end, + which verifies *in one run*: the config cascade + the `overrideconfig` CLI layer, the depcheck + pre-load VERSION graph **and** the post-load session audit (the aligned `cp` contract passes on a + real load), the reconciled servers (one-arg init + `startup[config]` + real `.z.pc` registration + through di.torq.handlers), and the app-code cascade + run hook. +- Full framework regression (each module in its own process): toml 60, log 4, config 58, depcheck + 120, handlers 160, servers 35, tplogmgr 12, di.torq 35 — **all green**. + +The core framework tier (log · toml · config · depcheck · handlers · servers · di.torq) is +reconciled and green. Remaining D5: the library/query tier — dataaccess, serverselect, pubsub, and +the vendored asyncdispatch/eodtime/dbwrite — plus the proc modules' own suites (which need those). diff --git a/docs/reconciliation/serverselect.md b/docs/reconciliation/serverselect.md new file mode 100644 index 00000000..26ddfbd1 --- /dev/null +++ b/docs/reconciliation/serverselect.md @@ -0,0 +1,87 @@ +# Reconciliation — `serverselect` (stays flat: `di.serverselect`) + +**Status:** LANDED + verified (129 k4unit + 67 integration assertions green). +**Decision:** canonical = **kdbx `feature-serverselect`, taken verbatim**. There was no +implementation contest to settle: TorqX's copy *is* this branch, vendored unchanged. +**Sides:** kdbx `origin/feature-serverselect:di/serverselect` · TorqX `di/serverselect` (vendored) + +## Why this one is trivial + +TorqX never wrote a serverselect. It **vendored the branch tip verbatim** (source commit `d8167c3`, +2026-07-14) so the POC built on the in-progress official work instead of diverging. Verified this +session with a full recursive diff: `serverselect.q`, `serverselect.md`, `test.csv` and +`integration.q` are **byte-identical** to the branch tip, which has not moved since. TorqX's only +additions were a `VERSION` file, a `version` export, and a header comment recording the vendoring. + +So this reconciliation is: take the branch files as-is, keep the two version grafts, drop the +now-meaningless vendoring note. This matches the RFC-0001 appendix action for the module +(*"drop vendored copy; track the branch"*). + +It is also self-contained — `serverselect.q` `use`s **no** `di.*` module (logging is injected as a +binary `` `info`warn`error `` dict, matching di.torq's inject contract; `kx.log` appears only in +`integration.q`'s final step). So none of the `di.log`→`di.util.log` / +`di.handlers`→`di.torq.handlers` rename grafts the framework-tier modules needed apply here. + +## Naming: deliberately **not** renamed into the hierarchy + +Unlike the framework tier, this module keeps its flat `di.serverselect` name. Three reasons, all +pointing the same way: + +- `CLAUDE.md` puts the reusable library layer and everything tracking a `kdbx-modules` branch at + flat `di.*`, and says the existing flat modules are renamed into the hierarchy **later, in one + coordinated change (RFC phase 5)** — *don't pre-rename ahead of it*. +- Renaming would fork a module whose canonical home is an unmerged branch, turning a no-op merge + into a conflicted one. +- Its consumers and tests already bake in the flat name: `di/proc/gateway/deps.toml` declares + `"di.serverselect"`, and `test.csv:193` asserts the literal `"di.serverselect"` error prefix. + +This is the one deviation from the framework-tier method (`di.torq.*`/`di.util.*` renames) — the +rename is deferred to phase 5, not skipped. + +## Changes applied + +Placed at `di/serverselect` (flat), byte-identical to `origin/feature-serverselect` except: + +- **`VERSION` (0.1.0)** — new file. +- **`version:first read0`:::VERSION`** in `init.q`, added to the `export` list. + +Both grafts are **required**, not cosmetic, because `di/proc/gateway/deps.toml` declares +`"di.serverselect" = "0.1.0"` and di.torq now runs *both* depcheck phases on every startup: + +| depcheck phase | reads | without the graft | +| --- | --- | --- | +| pre-load version graph (`checkversiongraph*`) | the on-disk `VERSION` file, no code load | `depcheck.q:351` — *"has no VERSION file at …"* | +| post-load session audit (`checkdeps`) | the loaded module's **`version` export** | `depcheck.q:223-226` — *"…exports no version"* | + +Either one fails a real `gateway` startup. Adding `version` to the export dict is safe here +(unlike toml/config/depcheck/servers, where it would break their `getapimeta` contract test): +serverselect has no `getapimeta` and no test asserting its exact export set. + +`serverselect` correctly ships **no `deps.toml`** — it has no peers to declare, so it is a safe +leaf and the manifest walk stops there. + +## Verification + +- **k4unit `di.serverselect`: 129/129 green** (registration, selection strategies, attribute + routing, argument validation, injected-logger capture, init error prefixes). +- **`integration.q`: 67/67, exit 0** — the standalone real-process test, run unsandboxed so the + spawned child listeners can `bind()`. It launches genuine child q backends, opens real IPC + handles, and routes live queries to the selected handle, so the selection functions are proven to + hand back handles that actually answer. +- **Both depcheck integration points proven** against the exported API: `checkversiongraphfile` + passes a manifest requiring `di.serverselect` at 0.1.0 and raises the correctly attributed + `(required by di.proc.gateway) …` failure at an unmeetable 9.9.9; the `version` export reads back + as `"0.1.0"`. +- **Regression, each in its own process:** depcheck 120/120, di.torq 35/35 — a new module on QPATH + changed nothing. + +## Feeding back to the branch + +Nothing to send back as a fix — the implementation is untouched. The only delta to carry when +`feature-serverselect` merges is the two version grafts (`VERSION` + the `version` export), a +cherry-pickable two-line change. Worth raising with the author as a general convention point rather +than a serverselect bug: any module that a shipped `deps.toml` declares needs both. + +`di.proc.gateway` is still inert on this branch — it also `use`s `di.asyncdispatch` and +`di.dataaccess`, neither yet reconciled. Remaining D5: dataaccess, pubsub, subscriptions, and the +vendored asyncdispatch(→asyncutil)/eodtime/dbwrite, then the proc modules' own suites. diff --git a/docs/reconciliation/toml.md b/docs/reconciliation/toml.md new file mode 100644 index 00000000..a3eccf30 --- /dev/null +++ b/docs/reconciliation/toml.md @@ -0,0 +1,50 @@ +# Reconciliation — `toml` → `di.util.toml` + +**Status:** RECOMMENDED (landed in working tree; awaiting `feature-toml` author sign-off) +**Decision:** canonical = **kdbx `feature-toml` implementation**; TorqX `di.util.toml` retired. +**Sides:** kdbx `origin/feature-toml:di/toml` · TorqX `di/util/toml` + +## Why kdbx's implementation wins + +Both were built to the same scoped-down spec (the TorQ-FSP settings survey — identical +supported/unsupported feature lists, both policy-free: TOML strings → q char strings, never +symbols). kdbx's is the more robust and more framework-integrated: + +- **Escape-aware in-string masking** (`instrmask`) correctly handles `\"` *inside* a string. + TorqX's `firstunquoted` used `mod[;2]sums s="\""`, which miscounts an escaped quote as + toggling string state — so a `#`/`,`/`=` after an escaped quote could be misread. +- **Fail-loud throughout:** validates bare-key charset, rejects dotted keys, **detects duplicate + keys/sections** (a real TOML error — TorqX silently last-wins), rejects malformed arrays, + unterminated arrays, unparseable scalars, and non-string input. TorqX could yield silent nulls. +- **Single-pass `unescape`** resolves `\\` adjacent to an escape char correctly; TorqX used an + ordered `ssr` chain that mishandles that case. +- **`getapimeta`** — callable-API metadata for `di.torq` to register with `di.api`. TorqX had none. +- Its test.csv (60 checks) is materially stronger, and already asserts the `[dependencies]` + deps.toml contract that `di.depcheck.readdeps` consumes, plus the `getapimeta` contract. + +TorqX's only edges were narrow: a `VERSION` file/`version` export, the hierarchy-correct error +prefix, and `parsefile` returning `()!()` on a missing file. First two are grafted below; the +third is a deliberate design difference (see Follow-ups). + +## Changes applied on placement + +- Placed at **`di/util/toml`** (the `di.util.*` tier), not flat `di/toml`. +- `di.toml` → `di.util.toml` throughout (error-message prefixes, comments, docs, `use\`di.util.toml`, + fixture load path `di/util/toml/test.q`). +- Added a **`VERSION`** file (`0.1.0`) so `di.depcheck`'s manifest walk (which reads VERSION from + disk) has a version to compare. **Not** added `version` to the export dict on purpose — that + would break kdbx toml's `getapimeta` contract test (exports-except-`getapimeta` must equal the + documented API). VERSION-on-disk is sufficient for depcheck. +- Verified: **`di.util.toml` k4unit 60/60 green** on `feature-torqx`. + +## Follow-ups / author review notes + +- **`parsefile` on a missing file SIGNALS** (kdbx: fail-loud, caller guards existence) vs TorqX's + `()!()`. Kept kdbx's behaviour. **Downstream:** `di.torq.config`'s cascade probes optional + `.toml` tiers and currently relies on the empty-dict return (config.q:43-45). When `config` is + reconciled, its `parsefile` wrapper must guard `.toml` existence the same way it already guards + `.q` (`if[0=count key hsym\`$path; :()!()]`) — kdbx's own `feature-config` reportedly already + does this. Tracked as a note for the **config** reconciliation step; no live consumer on the + branch depends on it yet. +- `feature-toml` can be closed as superseded once its author confirms nothing else on the branch + depends on the flat `di/toml` path. Work carried with attribution to the original author. diff --git a/docs/rfc-0001-torqx-kdbx-consolidation.md b/docs/rfc-0001-torqx-kdbx-consolidation.md new file mode 100644 index 00000000..1f62c195 --- /dev/null +++ b/docs/rfc-0001-torqx-kdbx-consolidation.md @@ -0,0 +1,240 @@ +# RFC-0001 — Consolidating TorqX and kdbx-modules + +- **Status:** Draft — for discussion +- **Author:** Jamie Grant +- **Audience:** Jonny Press (plan owner) + kdbx-modules contributors +- **Related:** [TorQ Modularisation Plan](https://data-intellect.atlassian.net/wiki/spaces/TK/pages/2375450629) · [TorqX POC: Status & Design Findings](https://data-intellect.atlassian.net/wiki/spaces/TK/pages/2646409222) + +> This RFC proposes how to merge the TorqX effort and the kdbx-modules sprint work into one +> aligned codebase, and asks for decisions on the handful of choices that gate everything else. +> It does **not** change the plan's design principles (DI, the tier model, versioning-by-QPATH); +> it's about *consolidation mechanics and naming*. Nothing merges until the decisions below land. + +--- + +## 1. TL;DR + +TorqX (a de-risking spike) has grown into a working implementation of the plan's entire +**orchestration / process / query tier** — modules that in kdbx-modules exist only as unmerged +feature branches or not at all. In doing so it made several **design choices that diverge from the +plan** (a namespace hierarchy, `di.servers` injected, per-module dependency manifests) and now +holds **parallel implementations** of a set of modules that kdbx-modules contributors are also +building. We should consolidate before the divergence gets more expensive. + +**Decisions requested** (detail in §4): + +| # | Decision | Recommendation | +|---|---|---| +| D1 | Module naming: flat `di.*` vs hierarchy `di.proc.*`/`di.torq.*`/`di.util.*` | Adopt the hierarchy — *but this is the highest-cost call; see §4* | +| D2 | Base repo: kdbx-modules vs TorqX | **kdbx-modules** as git base; merge TorqX in | +| D3 | Topology: one repo vs framework-depends-on-library | One repo | +| D4 | In-flight branches/PRs: drain-then-migrate vs rebase | Drain the near-done, rebase the rest | +| D5 | Per-module canonical implementation (where both exist) | Case-by-case with the branch author (§ appendix) | + +The naming decision (D1) is the one that blocks in-flight work and downstream consumers; please +prioritise it. + +--- + +## 2. Why now + +Two efforts are building the same thing from opposite ends: + +- **kdbx-modules** — the sprint-driven extraction. `main` holds the Tier-1 utility modules; the + framework/process tiers are in feature branches under active development by several people. +- **TorqX** — a spike that built top-down: the orchestrator (`di.torq`), the process types, the + gateway/query tier, and a round of DI/dependency-management hardening, all proven end-to-end. + +They now overlap on ~9 modules with **two independent implementations each**. Every week that +passes, the reconciliation cost rises and the risk of shipping divergent contracts grows. This is +the moment to align. + +--- + +## 3. Current state (from a checkout of both repos) + +**kdbx-modules `main`** — Tier-1 utilities, flat names: +`analytics asyncutil cache compression datadog dataloader k4unit memstats os pubsub querylog +simtick timer tz tplog`. No `.github/` CI, no git tags. Has `consistency.md`, `style.md`, an empty +`.claude/`, and `.reviewagent.yml`. + +**kdbx-modules feature branches** (framework/process work, unmerged): `feature-config`, +`feature-depcheck`, `feature-handlers`, `feature-logging`, `feature-dataaccess`, +`feature-serverselect`, `feature-asyncdispatch`, `feature-eodtime`, `feature/dbwritemodule`, +`feature-sort`, `feature-merge`, `feature-API`, `feature-kafka`, `extract-html`. + +**TorqX** — the framework/process/query tier, built and proven: +`di.torq` + `di.torq.{config,depcheck,servers,handlers,logroll}`, `di.util.{log,toml}`, +`di.proc.{hdb,rdb,wdb,tickerplant,gateway}`, `di.subscriptions`, `di.tplog`, `di.dataaccess`, +plus **vendored** copies of `asyncdispatch`, `serverselect`, `pubsub`, `dbwrite`, `eodtime` +(some patched — see appendix). Full k4unit regression green; stack boots + queries end-to-end. +Adds beyond the plan: the namespace hierarchy, injected `di.servers`, per-module `deps.toml` + +a startup dependency-graph check, and an operational layer (`torqx.sh`, `export-systemd`, tmux dev +mode) shipped inside the `di.torq` module at `di/torq/bin/`. + +**The key point:** merging is **not a file-move**. For ~9 modules there are two implementations +that must be reconciled module-by-module with their authors (see appendix). + +--- + +## 4. Decisions requested + +### D1 — Module naming: flat vs hierarchy + +The plan uses **flat** `di.*` names across five conceptual tiers. TorqX introduced a **namespace +hierarchy** that maps onto those tiers: `di.proc.*` (process types), `di.torq.*` (orchestrator + +the machinery it owns), `di.util.*` (standalone utilities), with the library layer and all +vendored/upstream modules staying flat. + +- **For:** groups ~16+ authored modules by role instead of a flat list of 30+; makes "what is + this module's job" legible; kdb-x supports it natively (a parent can be a module *and* hold + children; loading a child doesn't load the parent — verified). +- **Against:** it is a **breaking change** — every `use`di.rdb`` becomes `use`di.proc.rdb``, so + every open PR/branch and every downstream consumer must change; and it revises the plan's stated + design. + +If we adopt a hierarchy, a sub-decision: **`di.torq.*` vs `di.core.*`** for the framework +machinery. `di.torq.servers` reads as "servers belongs to the orchestrator"; `di.core.servers` +reads as "a core framework module, peer to di.torq." TorqX currently uses `di.torq.*`. + +> **Recommendation:** adopt the hierarchy — it's a real, low-controversy-once-settled improvement +> and it's already proven. But it is the **highest-cost, least-reversible** decision here, so it +> must be made deliberately and *before* any branch merges (renaming after contributors build on +> flat names is far more expensive). If the appetite for a breaking rename isn't there, the +> fallback is: keep flat names for now, keep the hierarchy as a documented future option. I lean +> `di.torq.*` but am genuinely open on the sub-decision. + +**This decision gates all merge work.** + +### D2 — Which repo is the base + +Instinct is often "make the more-complete repo (TorqX) the new main." I'd argue the base-repo +choice should be decided on **community and continuity, not capability**, because the hierarchy and +the TorqX designs can win *regardless* of which git history is the base: + +- **kdbx-modules as base** — preserves contributors, open PRs, the review bot, the established name + and download URLs. TorqX's biggest contribution (the whole orchestration/process tier) fills + **empty** sprints, so it lands as additive modules, not collisions. The hierarchy can still be + adopted repo-wide as part of the consolidation. +- **TorqX as base** — starts from the coherent single-author design + hierarchy already in place, + but orphans kdbx-modules' contributors/PRs/tooling/name and still requires importing ~15 utility + modules from it. + +> **Recommendation: kdbx-modules stays the base repo; merge TorqX into it.** You keep the +> community and lose only the "TorqX" repo name — the cheapest thing to give up. + +### D3 — Repo topology: one repo or two layers + +The plan says "import one module for a capability, or import `di.torq` for the full stack" — which +argues for **one** repo containing everything. TorqX's vendoring pattern hints at an alternative: +`kdbx-modules` = the module *library*, a separate `TorqX` = the *framework/reference-app* +(`di.torq` + processes) that depends on it. + +> **Recommendation: one repo.** Simpler for contributors, versioning, and CI at this stage; revisit +> a split only if the library genuinely needs an independent release cadence. + +### D4 — In-flight branches and PRs + +Adopting the hierarchy (D1) breaks every open branch. Options: **drain** (merge the near-complete +branches to `main` *first*, then migrate everything together) or **rebase** (each author re-bases +their branch onto the new scheme). Realistically it's both: drain what's close, rebase the rest — +but the sequencing must be explicit so no one's work is silently orphaned. + +> **Recommendation:** freeze new framework-branch work; land the branches that are review-ready; +> then do the naming migration in one coordinated change; rebase the remainder with author help. + +### D5 — Canonical implementation per overlapping module + +For each module that exists on both sides (§appendix), pick the canonical implementation *with the +branch author in the loop* — theirs, TorqX's, or a merge. Our per-module `deps.toml` + the +`di.depcheck` graph is a useful tool during this phase (declare peer versions, catch mismatches as +modules move). + +--- + +## 5. Recommended end-state (synthesis) + +One repo (**kdbx-modules**, kept as base), containing every module under an agreed **hierarchy**, +with the TorqX orchestration/process/query tier merged in, the overlapping modules reconciled to a +single canonical implementation each, vendored patches contributed back with attribution, a +licensed CI running the k4unit regression on every PR, the shared conventions in +`consistency.md`/`style.md` (extended) + a root `CLAUDE.md`, and a branch/PR workflow open to +contributors. + +--- + +## 6. Migration plan (phased) + +1. **Decisions** — this RFC signed off (D1–D5). *Nothing merges before this.* +2. **Context docs** — land `CLAUDE.md` + the extended `consistency.md`/`style.md` (drafted; + distilled from the TorqX findings) into the base repo, to set conventions for contributors. +3. **CI with licence** — stand up a runner with the corporate `k4.lic` (secret / self-hosted) that + runs the k4unit regression, including the spawn-heavy suites (real ports). *This is the biggest + net-new build and what makes the PR workflow safe.* +4. **Consolidate, in dependency order:** + a. utility modules (kdbx-only) — adopt as-is (place under the agreed scheme). + b. TorqX-only tier (orchestrator/process/query) — additive, brings in the empty sprints. + c. overlapping modules — reconcile per D5, author in the loop. + d. vendored patches — contribute back to the origin branches as **attributed** PRs; retire the + vendored copies. Resolve the `di.tplog` (lifecycle) vs kdbx `di.tplog` (= check/repair, our + `di.tplogutils`) **name collision**. +5. **Naming migration** — apply the agreed scheme repo-wide in one coordinated change (if D1 = + hierarchy). Provide a compat shim / codemod note for downstream consumers. +6. **Governance** — branch-protect `main`, require PR + review (align with `.reviewagent.yml`), add + `CODEOWNERS` + `CONTRIBUTING.md`, agree a monorepo **tag/release** convention (none exist yet). +7. **Open the workflow** to collaborators. + +--- + +## 7. Risks & mitigations + +| Risk | Mitigation | +|---|---| +| Hierarchy rename breaks every `use` + open PR | Decide D1 first; migrate in one coordinated change; codemod + compat note | +| Orphaning contributors' branches | Drain review-ready branches first; rebase the rest *with* authors (D4) | +| Vendored patches land un-attributed | Contribute back as PRs to the origin branches, crediting original authors | +| No CI → regressions merge silently | Phase 3 (licensed CI) before opening the PR workflow | +| `di.tplog` name collision | Resolve explicitly during phase 4d | +| Downstream users stranded by rename | `di.torq` compat shim (already in the plan) before onboarding real users | +| Two implementations silently diverge further | Freeze framework-branch work at phase 1 | + +--- + +## 8. Non-goals + +- Re-litigating the DI principle, the tier model, versioning-by-QPATH, or FinSpace removal — all + stand as the plan states. +- Building the remaining unbuilt tiers (IDB, monitor, DQC/DQE, discovery, …) — separate sprints. + +--- + +## 9. Open questions + +- D1 sub-decision: `di.torq.*` vs `di.core.*` for framework machinery. +- Release/tagging model for a monorepo of independently-versioned modules (the plan assumes tagged + releases; none exist yet). +- Where the operational layer (`torqx.sh`/`export-systemd`) belongs long-term — inside `di.torq` + (current TorqX choice) or a separate ops module. + +--- + +## Appendix — module reconciliation matrix + +"Canonical" and "Action" are proposals for discussion, not decisions. + +| Module | kdbx-modules | TorqX | Proposed canonical | Action | +|---|---|---|---|---| +| log / logging | `feature-logging` | `di.util.log` (built) | reconcile | compare contracts; pick one | +| config | `feature-config` | `di.torq.config` (built) | reconcile | compare; TorqX has the cascade + `.toml` | +| depcheck | `feature-depcheck` | `di.torq.depcheck` (built, + manifest graph) | reconcile | TorqX superset (graph) — verify vs branch | +| handlers | `feature-handlers` | `di.torq.handlers` (built; was `di.zed`) | reconcile | compare `.z.*` registry designs | +| dataaccess | `feature-dataaccess` | `di.dataaccess` (rebuilt; branch didn't fit) | likely TorqX | confirm with branch author | +| serverselect | `feature-serverselect` | vendored (unpatched) | **branch** | drop vendored copy; track the branch | +| asyncdispatch | `feature-asyncdispatch` | vendored + **patched** (callback-baking) | branch + our patch | PR the patch back, attributed | +| eodtime | `feature-eodtime` | vendored + **patched** (`di.tz`) | branch + our fix | PR the fix back | +| dbwrite | `feature/dbwritemodule` | vendored | branch | PR the enum-dir suggestion back | +| pubsub | `main` | vendored + **patched** (`callendofday` 2-list) | main + our patch | PR the patch back | +| tplog | `main` = check/repair (**our** `tplogutils`) | `di.tplog` = lifecycle | **both, renamed** | resolve the name collision | +| timer, tz, os, cache, compression, dataloader, simtick, k4unit, querylog, memstats, analytics, datadog, asyncutil | `main` | consumed (external) | kdbx | adopt as-is under the agreed scheme | +| torq, servers, subscriptions, rdb, wdb, hdb, tickerplant, gateway, logroll, toml | — | built | **TorqX** | additive — fills empty sprints | +| sort, merge, API, kafka, html | branches | — | kdbx | out of scope here; land via their branches | diff --git a/style.md b/style.md index f7d9413b..19324e52 100644 --- a/style.md +++ b/style.md @@ -128,3 +128,20 @@ Do not use windows carriage returns `^M` in q files. You can fix this by using dos2unix. Unless it is unavoidable lines of code should not exceed 150 characters. + +## Notes (framework tier) + +> Additive clarifications from the framework work; consistent with the rules above. + +- **Root writes across the module boundary are not gratuitous `::`.** The "avoid global assign" + rule stands, but `@[`.;name;…]` / `set[`.ns.fn;…]` used to maintain a *root* table or publish a + root IPC entry point from inside a `use`-loaded module are the **sanctioned idiom** (see the + namespace-write boundary in `consistency.md`), not a style violation. +- **`do` / `while` / `for`:** the iterator-first rule stands. A bounded queue/accumulator loop + with no natural iterator (e.g. a cycle-guarded dependency-graph walk) is the rare justified + exception — comment *why*. +- **Reserved names bite at load time, not just runtime.** Beyond "don't use q reserved names": + the ones that have actually broken things are `log`, `ss`, `sv`, `string`, `cut`, `tables`. A + local or parameter named after a builtin may fail to shadow it and can throw when the file is + *loaded* (e.g. `sv:...` → `'sv`). Pick a distinct name (`srv` not `sv`, `lg` not `log`). Full + list of q traps in `CLAUDE.md`.