Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -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 `<name>.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="<TorqX>:<kdbx-modules>:$HOME/.kx/mod"` — colon-separated, first match wins; `di.a.b`
looks for `<dir>/di/a/b/init.<ext>`. `$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/<path>/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` → `<qpathdir>/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).
120 changes: 115 additions & 5 deletions consistency.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
6 changes: 3 additions & 3 deletions di/api/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
```

Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion di/api/api.q
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
1 change: 1 addition & 0 deletions di/asyncdispatch/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
Loading