Repository navigation
Conversation
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>
| 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]; |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
Bug from TorQ - addressed in 2598c72.
Email send attempt is made, if successful the last time sent is recorded
| / daily: drop finished report jobs and schedule today's reports | ||
| datecheck:{[] | ||
| flushtimer[]; | ||
| @[runreport each;0!activereports[];{write[0;x;1b]}]; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; | ||
|
|
There was a problem hiding this comment.
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.
DIReview Summary1 critical | 2 warning(s) | 1 suggestion(s)
Suggestions
|
- 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 |
There was a problem hiding this comment.
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.
DIReview Summary0 critical | 1 warning(s) | 1 suggestion(s)
Suggestions
|
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; | ||
| }; | ||
|
|
There was a problem hiding this comment.
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 -------- |
There was a problem hiding this comment.
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.
DIReview Summary0 critical | 2 warning(s) | 0 suggestion(s)
|
| / daily: drop finished report jobs and schedule today's reports | ||
| datecheck:{[] | ||
| flushtimer[]; | ||
| @[runreport each;0!activereports[];{write[0;x;1b]}]; |
There was a problem hiding this comment.
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
| .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; |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
We want to require every expected key and name any that are missing - will update
| 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}]; |
There was a problem hiding this comment.
should this be exit 1 as it's an error?
There was a problem hiding this comment.
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 $?" | ||
| }; |
There was a problem hiding this comment.
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.
DIReview Summary0 critical | 1 warning(s) | 0 suggestion(s)
|
Port
TorQ/code/processes/reporter.qandTorQ/code/common/monitoringchecks.qto TorqX. The reporterruns 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.memorycheckandfriends) become
di.torq.checks, whichdi.torqpublishes 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 mocklog,timerandserversdeps, a spawned target and aspawned fake gateway, so postbacks go over real IPC.
reporter.md,VERSION(0.1.0),deps.toml(di.util.cfg0.2.0,di.email0.1.0,di.os0.1.0).API
init[config;deps]versionEverything clients and csvs call by name is published at root under TorQ's names instead of exported:
postbackandgwpostback(the postback targets),runreportnow(new), the result handlersemailalert,emailreport,writetofiletype,writetosplayedandpublishresult, and the tablesreports,querystatus,querylogs,reporterprocessresultsandemailstats. A csv names itshandler by string, resolved at root, and the target and gateway post results back by name.
Dependencies
log,timer,servers.initerrors naming any that is missing.d:di.util.cfgfor settings and path roots,di.asyncutilforpostback,di.emailfor the email handlers,di.os` to delete temporary report files.initsets up its tables, timer jobs and root names only once; a secondinitchanges nothing.Config
Defaults live in
di/torq/settings/reporter.q. Each key is also read with a presence check and anequal code default.
inputcsvappconfig/reporter.csv, underTORQXAPPHOMEwritetostdout1b: eachquerylogsrow is also loggedflushqueryloginterval1D00:00:00:querylogsrows, andquerystatusrows for finished runs, older than this are flushed every 2 minutesconnections`gateway`rdb`hdbemail(enlist`enabled)!enlist 0b, passed todi.email'sinitEach 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
datecheckuses mode 1 so it stays on midnight.Differences from TorQ
Needed for TorqX, or fixes:
.servers.SERVERS. TorqXsets no
.proc.procname, so TorQ's code would have read`nontorq.rdb1), not its proctype (rdb).di.email. A send with email disabled is logged as disabled, not as failed.TorQ logged "Finished report" though the run was
E.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.mdexplains why and how to include one.end(say 09:50 for the report above) does notschedule it today and logs "no run left in today's window". Otherwise the timer ran it once at
end.emailalertrecords an alert as sent only once the send succeeds. TorQ recorded it before sending, soa failed send (say the mail server was briefly down) held the alert back for its whole
period.Tunless it already errored. TorQ decided for thewhole batch from the first run's stage, so one errored run left the others showing
Rfor good.querystatusalong withquerylogs, afterflushqueryloginterval.TorQ never cleared it, so it grew by a row per run until a restart. A run still going is kept.
updatestage(dead in TorQ too) is removed.Improvements, each small and unchanged for a working TorQ csv (reasons in
reporter.md):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).
runreportnow[name]sends a report straight away, whatever its window or day, and returns itsquery id.
late alert is not emailed and the timeout stays visible.
datecheckschedules each report on its own, so a failureis logged and the reports after it are still scheduled. TorQ trapped the whole list.
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 inreporter.md: a zeroperiod runs on every timer cycle, a run cannot be cancelled, and a run with a
0Wtimeout whose resultnever arrives blocks that report until a restart.
New module:
di/torq/checks/init.q,checks.q:tablecount,hdbdatecheck,memorycheck,symwcheck,slowsubscriber, withTorQ's messages.
test.q,test.csv,checks.md,VERSION(0.1.0).hdbdatechecknamesthe right tables when some are not loaded.
di.torq 0.9.0
torq.q: registerreporter->di.torq.proc.reporterin the built-in registry, andinitcheckspublishes
di.torq.checksas.checks.*on every process, after heartbeats. A report's query runson its target, so the checks must exist there, as
monitoringchecks.qdid in TorQ.settings/reporter.q: the shipped defaults.permissions/default.q: grantpostbackandgwpostbacktosystemuser. Targets and the gatewaypost results back to the reporter, which is refused without it.
torq.md: listreporteramong 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.qandtorq.md. Whichever merges second needs a rebase, and di.torq 0.10.0.Testing
k4unit:
k4unit.moduletestwas run in its own q process for each module, from the repo root.di.torq.proc.reporter: 135 tests, all passed. They cover:initrejecting missing deps with the dependency named, a failedinitregistering nothing, and a second
initchanging nothingstartupnextperiod'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
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
with a bad csv exiting 1 (with a control process that exits 0)
logged step, a failing handler ending "Finished report with errors", a remote error naming the
procname, and an unknown or disconnected process
T, several runs timing out at once with one alreadyerrored, a late result ignored, and the report sendable again
runreportnowfor a report not scheduled today, and an unknown nameemailalertsend not being recorded, the querylogs andquerystatus flush, and the
writecustomhookdi.torq.checks: 27 tests, all passed, with expected messages written from TorQ's source and a real50MB backlog for
slowsubscriber.di.torq: 110 tests, all passed.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):
.checks.*reports on rdb1 and one gateway report ran every minute and completed; the gatewayreport wrote its csv to
data/reports/.runreportnowover IPC returned its query id and the report completed.emailreportsent its attachment to the capture server and removed its temporary file.attachments match.
di.emailsends noDate:header and no logo, and the footer has noprocess details; these are left for
di.email.The POC changes are in TorqX-POC's
feature-reporterbranch.