Skip to content

di.torq.proc.reporter: port TorQ's reporter process - #169

Open
nicolew02 wants to merge 9 commits into
mainfrom
feature-reporter
Open

nicolew02 wants to merge 9 commits into
mainfrom
feature-reporter

Conversation

@nicolew02

@nicolew02 nicolew02 commented Dec 3, 2026 •

Copy link
Copy Markdown

Port TorQ/code/processes/reporter.q and TorQ/code/common/monitoringchecks.q to TorqX. The reporter
runs queries from a csv on a schedule, against one process or through the gateway, and passes each
result to a handler that emails it, writes it to a file or publishes it. Runs and their logs are kept in
root tables that clients query over IPC. The checks a report typically runs (.checks.memorycheck and
friends) become di.torq.checks, which di.torq publishes on every process.

New module: di/torq/proc/reporter/

  • init.q, reporter.q: the process. init[config;deps] follows the process-module convention.
  • test.q, test.csv: k4unit suite with mock log, timer and servers deps, a spawned target and a
    spawned fake gateway, so postbacks go over real IPC.
  • reporter.md, VERSION (0.1.0), deps.toml (di.util.cfg 0.2.0, di.email 0.1.0, di.os 0.1.0).

API

Export TorQ equivalent
init[config;deps] the file's top-level startup code
version

Everything clients and csvs call by name is published at root under TorQ's names instead of exported:
postback and gwpostback (the postback targets), runreportnow (new), the result handlers
emailalert, emailreport, writetofiletype, writetosplayed and publishresult, and the tables
reports, querystatus, querylogs, reporterprocessresults and emailstats. A csv names its
handler by string, resolved at root, and the target and gateway post results back by name.

Dependencies

  • Injected: log, timer, servers. init errors naming any that is missing.
  • used: di.util.cfgfor settings and path roots,di.asyncutilforpostback, di.emailfor the email handlers,di.os` to delete temporary report files.
  • init sets up its tables, timer jobs and root names only once; a second init changes nothing.

Config

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

Key Default
inputcsv appconfig/reporter.csv, under TORQXAPPHOME
writetostdout 1b: each querylogs row is also logged
flushqueryloginterval 1D00:00:00: querylogs rows, and querystatus rows for finished runs, older than this are flushed every 2 minutes
connections `gateway`rdb`hdb
email (enlist`enabled)!enlist 0b, passed to di.email's init

Each report is a timer job in di.timer mode 3 (next run one period after the previous run ends), which
matches TorQ's mode 2. The midnight datecheck uses mode 1 so it stays on midnight.

Differences from TorQ

Needed for TorqX, or fixes:

  • Each result is named with the target's procname and proctype, read from .servers.SERVERS. TorqX
    sets no .proc.procname, so TorQ's code would have read `nontorq.
  • A query that fails on the target is logged with its procname (rdb1), not its proctype (rdb).
  • The error for a failed send to the gateway is built correctly; TorQ's signalled a type error instead.
  • Email goes through di.email. A send with email disabled is logged as disabled, not as failed.
  • A run whose handler logged a failure (such as a failed email) ends "Finished report with errors";
    TorQ logged "Finished report" though the run was E.
  • A report scheduled before its window opens first runs at the window start. TorQ ran it one period
    early (08:45 for a 09:00 to 10:00 report every 15 minutes). As in TorQ, there is no run exactly at
    end; reporter.md explains why and how to include one.
  • A reporter started after a report's last slot before end (say 09:50 for the report above) does not
    schedule it today and logs "no run left in today's window". Otherwise the timer ran it once at end.
  • emailalert records an alert as sent only once the send succeeds. TorQ recorded it before sending, so
    a failed send (say the mail server was briefly down) held the alert back for its whole period.
  • When several runs time out at once, each is marked T unless it already errored. TorQ decided for the
    whole batch from the first run's stage, so one errored run left the others showing R for good.
  • Finished runs are flushed from querystatus along with querylogs, after flushqueryloginterval.
    TorQ never cleared it, so it grew by a row per run until a restart. A run still going is kept.
  • An unreachable branch of updatestage (dead in TorQ too) is removed.

Improvements, each small and unchanged for a working TorQ csv (reasons in reporter.md):

  1. Precise csv errors. Every problem is listed at once, by line, e.g.
    File not loaded: line 4: null value in timeoutinterval; line 4: joinfunction cannot be null if gateway is not null; line 3: resulthandler does not parse.
    TorQ gave one message for the whole file and found a bad query or handler only when the report ran.
    A bad csv stops the process with exit code 1 (TorQ exited 0).
  2. runreportnow[name] sends a report straight away, whatever its window or day, and returns its
    query id.
  3. No overlapping runs. A report still running from its last slot is skipped and the skip is logged.
  4. Late results are ignored. A result arriving after its run timed out is logged and dropped, so a
    late alert is not emailed and the timeout stays visible.
  5. One bad report does not stop the rest. datecheck schedules each report on its own, so a failure
    is logged and the reports after it are still scheduled. TorQ trapped the whole list.
  6. Results are checked for missing keys. A posted-back result must have every expected key, and any
    missing ones are named in the error. Extra keys are allowed. TorQ only rejected a result missing every key.

Not ported: nothing from reporter.q. Kept as in TorQ and listed as future work in reporter.md: a zero
period runs on every timer cycle, a run cannot be cancelled, and a run with a 0W timeout whose result
never arrives blocks that report until a restart.

New module: di/torq/checks/

  • init.q, checks.q: tablecount, hdbdatecheck, memorycheck, symwcheck, slowsubscriber, with
    TorQ's messages.
  • test.q, test.csv, checks.md, VERSION (0.1.0).
  • Each check returns one row per message; TorQ's returned one row per character. hdbdatecheck names
    the right tables when some are not loaded.

di.torq 0.9.0

  • torq.q: register reporter -> di.torq.proc.reporter in the built-in registry, and initchecks
    publishes di.torq.checks as .checks.* on every process, after heartbeats. A report's query runs
    on its target, so the checks must exist there, as monitoringchecks.q did in TorQ.
  • settings/reporter.q: the shipped defaults.
  • permissions/default.q: grant postback and gwpostback to systemuser. Targets and the gateway
    post results back to the reporter, which is refused without it.
  • torq.md: list reporter among the built-ins, and a "Report checks" section.

This PR and #168 both bump di.torq to 0.9.0 and touch the built-in registry, permissions/default.q and
torq.md. Whichever merges second needs a rebase, and di.torq 0.10.0.

Testing

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

  • di.torq.proc.reporter: 135 tests, all passed. They cover:
    • the export set, init rejecting missing deps with the dependency named, a failed init
      registering nothing, and a second init changing nothing
    • the shipped defaults matching the code defaults
    • the housekeeping timer jobs, and the connections passed to startup
    • nextperiod's slots before, inside and after a window, a time part way through a slot's minute,
      and a zero period, using fixed times so results do not depend on when the suite runs
    • scheduling: a repeating report's job and first run at the next slot, a run-once report, a report
      for another day, a report whose window has ended, one with no slot left today, no double
      scheduling, flushing ended jobs, and a report that fails to schedule not stopping the ones after it
    • every csv rule by line, several problems at once, a missing column, a missing file, and a process
      with a bad csv exiting 1 (with a control process that exits 0)
    • a report sent to a spawned target: completion, the result named with the target process, each
      logged step, a failing handler ending "Finished report with errors", a remote error naming the
      procname, and an unknown or disconnected process
    • timeouts: the overlap skip, a run marked T, several runs timing out at once with one already
      errored, a late result ignored, and the report sendable again
    • a postback missing keys rejected with them named, and one with an extra key accepted
    • runreportnow for a report not scheduled today, and an unknown name
    • a handler named in the csv that is not defined being logged
    • a report through the spawned gateway, with the joined result
    • every result handler, including a failed emailalert send not being recorded, the querylogs and
      querystatus flush, and the writecustom hook
  • di.torq.checks: 27 tests, all passed, with expected messages written from TorQ's source and a real
    50MB backlog for slowsubscriber.
  • di.torq: 110 tests, all passed.
  • 13 deliberate breaks to the code each failed at least one test.

End to end on TorqX-POC (the full stack, with reporter1 added and email sent to a local capture
SMTP server, so nothing was delivered):

  • Two .checks.* reports on rdb1 and one gateway report ran every minute and completed; the gateway
    report wrote its csv to data/reports/.
  • runreportnow over IPC returned its query id and the report completed.
  • emailreport sent its attachment to the capture server and removed its temporary file.
  • The same email reports were run through TorQ's reporter for comparison: subjects, bodies and
    attachments match. di.email sends no Date: header and no logo, and the footer has no
    process details; these are left for di.email.

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

Adds di.torq.proc.reporter, a port of TorQ's code/processes/reporter.q, and
di.torq.checks, a port of code/common/monitoringchecks.q. di.torq registers the
reporter as a built-in process type and publishes the checks as .checks.* on
every process, since a report's query runs on its target.

Improvements on TorQ, each documented in reporter.md: precise csv errors by
line, runreportnow, no overlapping runs, late results ignored, the first run at
the window start, remote errors naming the process, and "Finished report with
errors" for a run that ended E.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@nicolew02
nicolew02 requested a review from DI-Dexter December 3, 2026 12:13
Comment thread di/torq/proc/reporter/reporter.q Outdated
res:(email`senddefault)`to`subject`body!(`$recipients;subject;{"<div>",x,"</div>"} each result`messages);
if[-1=res;:write[data`queryid;"emailalert: email is disabled, alert not sent: ",string data`name;0b]];
$[res;
write[data`queryid;"emailalert: sent email alert for alert: ",string data`name;0b];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

emailalert calls `emailstats upsert (data`procname;data`name;.z.p) before checking whether the email send succeeded (or was disabled). This means the lastsent timestamp is updated even when no email is actually sent — when res=-1 (email disabled) the function returns immediately after recording the send time, so the next call within period will be suppressed with "previous email was too soon", even though no email was ever delivered. The emailstats upsert should be moved to after a successful send (i.e. inside the $[res;... branch).

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.

Bug from TorQ - addressed in 2598c72.
Email send attempt is made, if successful the last time sent is recorded

Comment thread di/torq/proc/reporter/reporter.q Outdated
/ daily: drop finished report jobs and schedule today's reports
datecheck:{[]
flushtimer[];
@[runreport each;0!activereports[];{write[0;x;1b]}];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In nextperiod, when curr is exactly on the last slot (i.e. equal to end), first d where d>=curr returns that slot. But runreport guards with endts<.z.p (strict less-than) before calling nextperiod, so a report whose window has just ended at exactly .z.p will still try to schedule. The resulting st equals endts, and (.z.m.timeraddjob)is called withstartattime=maxtime=endts, which may or may not fire depending on the timer implementation. This is a narrow edge case but the guard should be endts<=.z.p` to match the "no run at end" semantics described in the docs.

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 2598c72.
The exact case (.z.p equal to end, to the nanosecond) is unlikely to happen in practice, but a nearby one could. For a 09:00 to 10:00 report every 15 minutes, a reporter restarted at 09:50 took the next slot, 10:00, as its first run. That gave startattime = maxtime = 10:00, so the timer ran it once at end, which normal running never does. A null slot (end off the period grid, restarted after the last slot) could also run it straight away.
Now, if the next slot after a (re)start is missing or is end itself, the report isn't scheduled today and the log says "no run left in today's window". Changing the guard to endts<=.z.p wouldn't cover this, since .z.p is still before end. Tests cover both cases.


/ called by name over IPC or from the csv, as in TorQ
rootapi:`postback`gwpostback`runreportnow`emailalert`emailreport`writetofiletype`writetosplayed`publishresult;

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 calls @[csvloader;inputcsv;{write[0;x;1b];exit 0}] using the bare local name inputcsv, but inputcsv was stored into .z.m.inputcsv on line 348 (not as a bare local). The bare name inputcsv resolves to whatever inputcsv is in scope — inside a use-loaded module, a bare write goes to the module's private namespace, so .z.m.inputcsv was set but inputcsv (the bare name read back here) will be whatever it was before init ran (likely undefined or the string from a prior call). The same pattern is used for writetostdout and flushqueryloginterval throughout the file. Fix: either read back via .z.m.inputcsv at every use site, or assign to a local with : and store a copy into .z.m.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

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

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

Suggestions

  • di/torq/proc/reporter/reporter.q:183 — finishquery is called with 0b for a timeout, and its body reads: $[st; update ... returntime:.z.p ... ; update time:.z.p,status:1b ...]. The comment says "a timeout (st 0b) sets status but not returntime" — but status:1b is hardcoded in the false branch, so a timed-out query is marked status:1b regardless of the st argument. The test at test.csv line 97 (true,0,0,q,"(1b;1b)~value exec last status,null last returntime from querystatus where name=slowq") asserts statusis1bafter a timeout, confirming this. Ifstatusis intended to mean "completed successfully", it should bestatus:st` in the false branch as well, mirroring the true branch; if it has a different meaning, the comment and the true-branch value are misleading.

- emailalert records an alert as sent only once the send succeeds, so a failed
  send is retried on the next run instead of holding the alert back for its
  whole period. TorQ recorded it before sending.
- A reporter started after a report's last slot before end does not schedule
  it today; the timer otherwise ran it once at end, which reporter.md says
  never happens.
- Say what querystatus status means (finished, however it ended; stage says
  how) and rename finishquery's flag to returned. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
true,0,0,q,"$[.z.t within 00:15 23:50;logged[`info;""*Not scheduling report lastslot: no run left in today's window""];1b]",1,,and the reason is logged
run,0,0,q,n:count scheduled; mpriv[`datecheck][],1,,run datecheck again
true,0,0,q,n=count scheduled,1,,a report already scheduled today is not scheduled again
run,0,0,q,"setpriv[`timerids;mpriv[`timerids],enlist[`reporter.old]!enlist .z.p-0D01]; mpriv[`flushtimer][]",1,,flush with one report window ended

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 test for the lastslot case checks logged[\info;"*Not scheduling report lastslot: ..."]but the matchingrunline uses report name ``lastslot while the following lines (noslot) use noslot ``. The logged message check at line 48 references lastslotby name — if therunreportcall forlastslotsucceeds silently (e.g. the conditional$[.z.t within ...;...;::]short-circuits near midnight), theloggedassertion still passes vacuously because it checks withlikeand the log may contain an older matching entry. This is the same near-midnight skip guard used throughout, so it is probably intentional, but the correctness of thelogged` assertion depends on the test not being skipped, which the guard does not enforce.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

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

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

Suggestions

  • di/torq/proc/reporter/reporter.q:139 — nextperiod returning null is used as a signal for "no slot left", but the guard (null st) or st>=endts also skips scheduling when nextperiod returns a value >= endts. If nextperiod can legitimately return endts itself (a slot exactly at end), this silently drops that run. The existing doc says there is no run at end, so the st>=endts branch is correct — but verify that nextperiod never returns a valid slot equal to endts that should be scheduled; if it can, the condition should be st>endts rather than st>=endts.

nicolew02 and others added 6 commits December 3, 2026 15:00
nextperiod now never returns end itself, so runreport only checks for null
when deciding there is no run left today. The scheduling tests use fixed
times instead of windows built around the clock, so they no longer skip near
midnight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comparing a minute slot with a timestamp truncates the timestamp to the
minute, so at 09:45:30 the 09:45 slot still counted as next and a report could
be scheduled in the past. Regression from the previous commit; a test with a
timestamp part way through a minute covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment the three multi-line functions that had none, give the functional
update in stringnestedlists its q-sql form, and remove blocks from
conditionals: sendinner calls senddirect or sendgateway, and emailalert
returns early on a failed send. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
checktimeout passes every overdue query at once, but updatestage decided for
the whole list from the first query's stage: if that one had already errored,
none of the others were marked T and they showed R for good. Same in TorQ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
querystatus gained a row per run and was never cleared (as in TorQ), so it
grew until a restart and the scans send and checktimeout make of it slowed
with it. flushquerylogs now also drops finished runs older than
flushqueryloginterval; a run still going is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
csvlines builds the "line n: msg" list once for every csv rule. checktimeout
drops a redundant null returntime test (not status already covers it), and
memorycheck/symwcheck read .Q.w[] once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
updatestage[qid;`T;.z.p];
{write[x`queryid;"Exceeded specified timeout value: ",string `time$x`timeout;0b]} each timedout;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

checktimeout now selects timed-out rows without the null returntime guard that was removed. A query whose returntime is already set (i.e. it already finished and returned a result) can still appear in the scan if .z.p > time+timeout and not status — but status being false (0b) on a returned query should be impossible only if finishquery always sets it. More critically, the not status guard was kept, but null returntime was dropped, meaning a row that has a returntime but status=0b (a half-updated row) could now be re-timed-out. The original code excluded already-returned rows via null returntime; removing that guard is a correctness regression. Restore null returntime to the where clause.

delete from `querystatus where status,time<=cutoff;
};

/ --- result handlers: named in the csv, resolved at root; each takes the result dictionary last --------

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In flushquerylogs, the new delete condition is status,time<=cutoff. Because q evaluates right-to-left with no precedence, this parses as status,(time<=cutoff) — a 2-item list — not status and time<=cutoff. The intended condition (finished AND old) should be written status and time<=cutoff.

@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

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

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

Comment thread di/torq/proc/reporter/reporter.q Outdated
/ daily: drop finished report jobs and schedule today's reports
datecheck:{[]
flushtimer[];
@[runreport each;0!activereports[];{write[0;x;1b]}];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

One failure here stops all subsequent runs, right?
Can we break it out so each run is trapped individually, does that make sense? e.g. {@[runreport;x;...]} each

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.

will do!

Comment thread di/torq/proc/reporter/reporter.q Outdated
.z.m.log[`error][`postbackinner;e:"Query execution failed on remote process ",(string result`procname),": ",7_res];
'e]];
dictkeys:@[cols;result;{.z.m.log[`error][`postbackinner;e:"Result is not a dictionary"];'e}];
if[all not dictkeys in wrappercols;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

should this be not all dictkeys in wrappercols?
currently it only fails if all of the dictkeys are missing, but it seems more likely we want to check if any of the expected ones are missing?

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.

We want to require every expected key and name any that are missing - will update

Comment thread di/torq/proc/reporter/reporter.q Outdated
emailconfig:opt[config;`email;()!()];
(email`init)[$[99h=type emailconfig;emailconfig;()!()];enlist[`log]!enlist deps`log];
/ a bad csv stops the process, as in TorQ
@[csvloader;inputcsv;{write[0;x;1b];exit 0}];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

should this be exit 1 as it's an error?

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.

Will change to exit 1, thanks!

- datecheck traps each report, so one that fails to schedule does not stop the rest
- postback rejects a result missing any expected key, naming them; extra keys are allowed
- a bad csv exits 1, not TorQ's 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
exitcode:{[file]
writefile["exit.q";exitsrc file];
"J"$first system "QPATH=",(first system "pwd")," timeout 20 ",QBIN," ",FIXDIR,"/exit.q -q </dev/null >/dev/null 2>&1; echo $?"
};

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 system call captures the q process output but echo $? captures the exit status of the timeout command, not the q process itself. When q exits 1, timeout exits 1 too — but when q exits 0 normally, timeout exits 0, so the control case works. However, if timeout itself times out (q hangs), it exits 124, which "J"$first system ..." will parse as 124j, not 0j or 1j, causing both the control test (0=exitcode ...) and the bad-csv test (1=exitcode ...) to pass silently instead of failing with a clear error. Additionally, "J"$first system ... will fail if system signals an error (non-zero exit of the outer shell). The old code used @[system;...;()] to swallow that error; the new code has no trap, so a shell failure (e.g. QBIN not found) will throw instead of returning a usable exit code. Wrap the system call: @[{"J"$first system x};...;{0Nj}] and handle the timeout/error case explicitly.

@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.

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.

3 participants