Skip to content

di.torq.proc.monitor: port TorQ's monitor process - #168

Open
nicolew02 wants to merge 11 commits into
mainfrom
feature-monitor
Open

nicolew02 wants to merge 11 commits into
mainfrom
feature-monitor

Conversation

@nicolew02

@nicolew02 nicolew02 commented Dec 2, 2026 •

Copy link
Copy Markdown

Port TorQ/code/processes/monitor.q and TorQ/code/monitor/checkmonitor.q to a built-in TorqX
process type. The monitor runs checks from a csv against named processes on a schedule, judges each
result with a named result checker, and keeps status and history in root tables that clients query
over IPC. Heartbeats are left to di.torq.heartbeat, which the monitor's settings switch to
subscribe to every process.

New module: di/torq/proc/monitor/

  • init.q, monitor.q: the process. init[config;deps] follows the process-module convention.
  • test.q, test.csv: k4unit suite with mock log, timer, handlers and servers deps, and a
    spawned peer for the end-to-end check path.
  • monitor.md, VERSION (0.1.0), deps.toml (di.util.cfg 0.2.0, di.torq.servers 0.8.1).

API

Export TorQ equivalent
init[config;deps] the file's top-level startup code
addcheck[dict] addcheck
copyconfig[checkid;procname] copyconfig
enablecheck[checkid] / disablecheck[checkid] enablecheck / disablecheck
updateconfig[checkid;key;value] updateconfig
forceconfig[checkid;dict] forceconfig
updateconfigfammet[family;metric;key;value] updateconfigfammet
currentstatus[checkids] currentstatus
statusbyfam[families] statusbyfam
timecheck[timespan] timecheck
version

Unlike filealerter, the API is also published at root under TorQ's bare names, with
checkresulthandler (the postback target), the four result checkers (checkcount, queuecheck,
truefalse, resulttrue) and the tables checkconfig, checkstatus, checktracker and logmsg.
TorQ clients call these by name over IPC, and check csvs name result checkers by string, resolved at
root.

Dependencies

  • Injected: log, timer, handlers, servers. init errors naming any that is missing.
  • used: di.util.cfg for settings coercion and path roots, and di.asyncutil for postback.
  • init registers its timer jobs, handlers and root names only once; a second init changes nothing.

Config

Defaults live in di/torq/settings/monitor.q. Each key is also read with a presence check and an
equal code default.

Key Default
configcsv appconfig/monitorconfig.csv, under TORQXAPPHOME
configstored "" (none); saved on exit and read instead of the csv, under TORQXDATAHOME
runcheckinterval 0D00:00:05
checkinginterval 0D00:00:07
lagtime 0D00:01:00
cleartrackinterval 0D01:00:00
agecheck 0D12:00:00
connections `ALL
logmsgsubscriber 0b

The settings file also sets heartbeatsubscribeenabled:1b and heartbeatsubscribetypes:`ALL for
di.torq.heartbeat. The three timer jobs use di.timer mode 2, which matches TorQ's .timer.repeat
default.

Differences from TorQ

  • A check on an unconnected process fails at once with "no handle connection" and is retried after
    lagtime. TorQ recorded the same status but still sent to the null handle, leaving the check
    "running" and an unanswered checktracker row until the lagtime timeout. The status is the same.
    TorQ timed out the first attempt after lagtime and then retried on every checkruntime tick (~7s), because
    nextrun never moved. The monitor now retries every lagtime
  • Checks use live handles only, so a restarted process is checked again once di.torq.servers
    reconnects it. TorQ re-dialled a dead process on every check run, which could block.
  • copyconfig copies the check it is given. TorQ's where checkid=checkid compared the column with
    itself, so it always copied the last check.
  • A missing check csv is logged and the monitor starts with no checks.
  • logmsg subscription is behind logmsgsubscriber, off by default: nothing publishes logmsg yet,
    so subscribing only made each process reject the unknown table.
  • A result for a run no longer in checktracker, or with a null runid, is logged and ignored. TorQ added a null row to checkstatus.

Not ported: the web UI (a separate PR to be made if decision to add is made), the Datadog result checker, and .checks.* from
monitoringchecks.q (nothing in TorQ uses it, and its HTML output suits the reporter more than the
monitor). Segmented tickerplants send no heartbeats, as in TorQ. Duplicate checks and retries to
processes that are not running are left as in TorQ and listed as future work in monitor.md.

di.torq.servers 0.8.1

  • register skips this process's own row (its proctype and procname). process.csv with
    connections:`ALL and discovery's getservices both list the caller, so every such process
    dialled itself during init and waited out hopentimeout. 0.3.0 excluded it; Feature rediscovery #138's port of TorQ's
    trackservers.q dropped the exclusion to match legacy. servers.md records the change.

di.torq 0.9.0

  • torq.q: register monitor -> di.torq.proc.monitor in the built-in registry.
  • settings/monitor.q: the shipped defaults.
  • permissions/default.q: grant checkresulthandler to systemuser. Checked processes post results
    back on the monitor's own handle with a null user, so without it every result was refused.
  • torq.md: list monitor among the built-ins.

Testing

k4unit: k4unit.moduletest was run in its own q process for each module, from the repo root.

  • di.torq.proc.monitor: 179 tests, all passed. They cover:
    • the export set, and every export failing with the init guard before init
    • init rejecting missing or malformed deps and unreadable settings, keeping the guard after a
      failed init, and a second init changing nothing
    • the shipped defaults matching the code defaults
    • timer jobs, handlers and root names registered once, and the connections passed to startup
    • loading the csv: one row on several processes, unparseable params, and a missing file
    • every admin function, including bad checkids, keys and types, and copyconfig copying the
      named check
    • a check with no connection: failed at once, retried after lagtime, nothing sent or tracked
    • a check sent to a spawned peer and its postback: pass, a result checker failing it, a remote
      error, a checker that is missing or returns a non-dictionary, and a result for a cleared run or with a null runid
    • checkruntime, cleartracker, currentstatus, statusbyfam and timecheck against known
      values
    • the four result checkers
    • logmsg: stored by the upd wrapper, not subscribed while logmsgsubscriber is off, subscribed
      once when on, and dropped on .z.pc
    • saving and reading the stored config on .z.exit
  • di.torq.servers: 82 tests, all passed, including a new one that fails without the register fix.
  • di.torq (110), di.torq.heartbeat (83), di.torq.proc.discovery (30) and di.permissions (58):
    all passed.
  • The module loads in a fresh q session without di.torq.

End to end on TorqX-POC (the full stack of 14 processes, with monitor1 started straight after
discovery1 so it learned every other process from discovery):

  • All six POC checks (trade count, heap size and subscriber queues) passed. Before the
    checkresulthandler grant, every result was refused by permissions; that run is what led to it.
  • monitor1 received heartbeats from every process except the segmented tickerplants, and never dialled
    itself.
  • A forced end of day on stp1 completed (sort1 wrote the hdb partition and reloaded hdb, rdb1, idb1
    and gateway1). monitor1's checks kept running and passing throughout, none stuck running, and no
    heartbeat went to warning.
  • No ERROR lines in monitor1's log. The only ERROR lines in the stack were stp1's and sctp1's
    "Table heartbeat not in list of stp pub/sub tables", present before and after end of day.

In a separate scratch stack, a check against a peer that was then killed failed with
"no handle connection", and addcheck over IPC added a check that ran against it.

The POC changes are in TorqX-POC's feature-monitor branch.

nicolew02 and others added 8 commits December 1, 2026 14:36
Port `TorQ/code/processes/monitor.q` and `TorQ/code/monitor/checkmonitor.q` to a built-in TorqX
process type. The monitor runs checks from a pipe-delimited csv against named processes on a
schedule, judges each result with a named result checker, and keeps status and history in root
tables that clients query over IPC. It also subscribes to `logmsg` on every process. Heartbeats
are left to `di.torq.heartbeat`, which the monitor's settings switch to subscribe to every process.

## New module: `di/torq/proc/monitor/`

- `init.q`, `monitor.q`: `init[config;deps]` with injected `log`, `timer`, `handlers` and `servers`;
  `use`s `di.util.cfg` and `di.asyncutil`. `init` is idempotent.
- Exports `init`, `addcheck`, `copyconfig`, `enablecheck`, `disablecheck`, `updateconfig`,
  `forceconfig`, `updateconfigfammet`, `currentstatus`, `statusbyfam`, `timecheck` and `version`.
- The API, `checkresulthandler`, the result checkers (`checkcount`, `queuecheck`, `truefalse`,
  `resulttrue`) and the `checkconfig`/`checkstatus`/`checktracker`/`logmsg` tables are published at
  root under TorQ's names, so TorQ clients and check csvs work unchanged.
- `test.q`, `test.csv`: 158 k4unit tests, including an end-to-end check against a spawned peer.
- `monitor.md`, `VERSION` (0.1.0), `deps.toml`.

## Framework changes

- `di/torq/torq.q`, `torq.md`: `monitor` is a built-in proctype; `di.torq` 0.9.0.
- `di/torq/settings/monitor.q`: defaults, plus heartbeat subscription to every process.
- `di/torq/permissions/default.q`: grant `checkresulthandler` to `systemuser`, as checked
  processes post results back with a null user.

## Differences from TorQ

- A check on a process with no connection is recorded at once and retried after `lagtime`; it is
  not sent, marked running or tracked.
- `copyconfig` copies the check it names (TorQ's `where checkid=checkid` always copied the last).
- A missing check csv is logged and the monitor starts with no checks.
- Not ported: the web UI (separate PR), the Datadog result checker, and `.checks.*` from
  `monitoringchecks.q`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ogmsgsubscriber

di.torq.servers 0.8.1: `register` skips this process's own row (its proctype and procname).
process.csv with `connections:`ALL` and discovery's getservices both list the caller, so
every such process dialled itself during init and waited out hopentimeout. 0.3.0 excluded it;
#138's port of TorQ's trackservers.q dropped the exclusion to match legacy. The servers suite
gains a row that fails without the fix.

di.torq.proc.monitor: new `logmsgsubscriber` setting, `0b` by default. Nothing publishes
`logmsg` yet, so subscribing only made every process reject the unknown table and the monitor
log an error per process. The monitor now declares di.torq.servers 0.8.1 in its deps.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments that restated a name are gone; the rest say the why in one line. No code changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- init: a second call returns before reading settings, so it changes nothing; the logger is set last,
  so a failed init leaves the init guard in place.
- checkresulthandler ignores a result whose run is no longer tracked, instead of adding a null
  checkstatus row (as TorQ did).
- monitor.md: list both, and that checks use live handles only (TorQ re-dialled on every run).
- Tests: the before-init tests assert the guard's message, timecheck is checked against known
  times, and the stored-config read restores a deleted check. The new tests fail on the old code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/ --- init ------------------------------------------------------------------------------------

/ called by name over IPC, as in TorQ
rootapi:`addcheck`copyconfig`disablecheck`enablecheck`updateconfig`forceconfig`updateconfigfammet,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

init sets .z.m.registered:1b (line 356) and .z.m.log (line 355) before calling inittables[], publishroot[], registerjobs deps, and initcheck[]. If any of those calls signal (e.g. a timer or handler registration error), registered is already 1b and log is already set, so the idempotency guard (if[registered;:…]) will treat the partially-initialised state as fully initialised on the next call, silently skipping re-registration. The fix is to set .z.m.registered:1b and .z.m.log only after all setup steps succeed, or use a separate initialising flag.

totaltime:`timespan$(); / execution plus network and queue time
timerstatus:`short$(); / 1 if it ran within runtime
running:`short$();
result:()); / error message

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inittables inserts a placeholder row into checktracker with a null checkid (0Ni) so that result stays a general list. This row has runid=0Ni. If a postback ever arrives with runid=0Ni (e.g. a malformed message), checkresulthandler will find it in checktracker, look up checkid=0Ni in checkconfig, and then attempt (getcheckconfig) 0Ni— which returns a row of nulls includingresultchecker:""andparams:()!(), producing a confusing error rather than the "ignoring result" warning. The placeholder row should use a sentinel that can never be a real runid, or the guard in checkresulthandlershould exclude0Ni` explicitly.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eedc7b3: checkresulthandler now ignores a null runid along with untracked ones, so a malformed postback can't match the placeholder row. Tests added and updated PR description

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 2 warning(s) | 4 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Suggestions

  • di/torq/proc/monitor/monitor.q:95 — The module-local subscribedhandles variable (line 27) is read inside the .z.pc handler lambda, but the lambda is not a closure over it — it reads the name subscribedhandles which will resolve to the module's private namespace copy only if called from the same frame. The lambda is registered as a root .z.pc handler via register and will be invoked from root context, where subscribedhandles does not exist. The fix is consistent with the rest of the file: use .z.m.subscribedhandles inside the lambda, e.g. {if[x;.z.m.subscribedhandles:.z.m.subscribedhandles except x]}.
  • di/torq/proc/monitor/monitor.q:110 — runcheck reads .z.m.runid and writes .z.m.runid+:1i, but runid is also referenced bare on line 111 ((asyncutilpostback)[enlist h;(remotecheck;(cquery;cparams);runid);checkresulthandler]) and on line 112 (checktracker insert (runid;…)). These bare runid reads will not see the module-private .z.m.runid when invoked from root context (via the timer). Fix: use .z.m.runid at both call sites inside runcheck.
  • di/torq/proc/monitor/monitor.q:128 — runnow reads lagtime bare (inside nohandle, which uses it), and checkruntime / cleartracker / runnow are called as timer job functions from root context. lagtime will not resolve to .z.m.lagtime from root. The same issue affects logmsgsubscriber in subscribenew (line 72), configcsv/storedconfig in initcheck (line 149/150), and runcheckinterval/checkinginterval/cleartrackinterval/agecheck/lagtime in registerjobs (lines 93-100) where they are passed as values to addjob — those are fine. The bare reads that fire from root timer/handler context are: lagtime in nohandle (line 108), logmsgsubscriber in subscribenew (line 73). Fix: replace each bare config-variable read in functions that execute from root with .z.m.<name>.
  • di/torq/proc/monitor/monitor.q:285 — copyconfig calls addcheck with the result of update process:newproc from delete checkid from exec from …. addcheck validates that family, metric, process are all symbols (11h=type). update process:newproc sets process to the atom newproc, which has type -11h, not 11h. The existing test passes a symbol atom for newproc, which would fail this check. If the type check in addcheck uses = rather than in against 11h, it will reject a scalar symbol. Confirm that the addcheck type guard accepts -11h (atom) as well as 11h (vector) for process, or enlist newproc before passing.

checkresulthandler's untracked-run guard matched checktracker's placeholder row, whose runid is
0Ni, so a malformed postback with a null runid added a null row to checkstatus. Null runids are
now ignored with the same warning. From review on #168.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
};

/ the postback target
checkresulthandler:{[x]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The or operand not r in exec runid from \checktrackeris evaluated unconditionally even whennull ris true, because q'soris not short-circuit. Ifchecktracker doesn't exist or is otherwise problematic this will still execute. More critically, a null integer (0Ni) will match any null integer already present in the runidcolumn ofchecktrackerviain— so the guardnull ris necessary to prevent the fallthrough, butorevaluates both sides regardless. The intent is correct only because thenull rcheck comes first and its result of1bORed with the second expression still gives1b, so the early-exit (:) fires. However, the right-hand side still executes a full table scan every time null ris true. This is a minor inefficiency/robustness issue; use$[null r;...;not r in ...]or sequentialif` guards to truly short-circuit.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 0 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

nicolew02 and others added 2 commits December 4, 2026 16:46
@[value;`x;{[c]}] applies the handler to the error and returns ::; it needs {{[c]}},
as .servers.addprocscustom already has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- requireinit checks registered; drop initialised[], which always agreed with it
- enablecheck/disablecheck name themselves in the init guard error, not togglecheck
- nohandle comment: TorQ retried every checkinginterval after the first timeout
- init.q header and deps.toml comment match what the module does
- monitor.md: where heartbeats are, configstored needed to keep IPC-added checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

/ set one params value; the key must exist and the type must match
updateconfig:{[cid;paramkey;newval]
requireinit[`updateconfig];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

togglecheck no longer calls requireinit, but disablecheck and enablecheck now wrap it and each call requireinit individually. Any direct caller of togglecheck (e.g. internal code or IPC clients that call it by name) will bypass the requireinit guard entirely. If togglecheck is meant to be an internal helper that is always reached through disablecheck/enablecheck, mark it private or rename it; if it is part of the public API, restore the requireinit call inside it.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

0 critical | 1 warning(s) | 2 suggestion(s)

⚠️ Spec check skipped — tracker lookup failed (NO_REF_FOUND). Standards axis only.

Suggestions

  • di/torq/proc/monitor/monitor.q:10 — registered is now a module-level variable set to 0b at load time, and requireinit reads it as a bare name. Under the module-namespace write boundary described in the consistency guide, init writes .z.m.registered:1b into the module's private namespace, but the bare registered read in requireinit on line 14 (if[not registered;) will also resolve within the same private namespace — so that part is consistent. However, registered is initialised at load (registered:0b) rather than through .z.m, meaning if init is ever called a second time (the idempotency case the comment mentions), .z.m.registered is reset to 1b correctly, but a reload of the module file would reset the bare registered to 0b without touching .z.m.registered, leaving the two out of sync. Store the flag consistently: either always use .z.m.registered (set it in the module body too, e.g. .z.m.registered:0b) or always use a bare name and write it with a bare assign inside init.
  • di/torq/servers/servers.q:395 — The default value for .servers.connectcustom has changed from {[connectedrows]} (a function that accepts one argument and returns the argument — a no-op identity) to {{[connectedrows]}} (a function that returns an inner lambda {[connectedrows]} without calling it, i.e. it ignores its argument and returns a function value). This means every call to .servers.connectcustom[rows] when no prior definition exists will now return a function object instead of executing the hook, silently doing nothing with connectedrows. The fix is to revert to the single-brace form: {[connectedrows]}, matching the already-corrected .servers.addprocscustom on the next line which correctly uses the double-brace {{[connectiontab;procs]}} because an inner lambda that accepts two args is the intended no-op there — but for .servers.connectcustom the intent was simply a no-op body, not returning a lambda.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants