Skip to content

di.clienttracking - #132

Merged
alowrydi merged 2 commits into
mainfrom
feature-clienttrackingv2
Sep 18, 2026
Merged

alowrydi merged 2 commits into
mainfrom
feature-clienttrackingv2

Conversation

@alowrydi

Copy link
Copy Markdown
Collaborator

Add di.clienttracking - inbound client session tracking and usage counting

Summary

A kdb-x module for TorQ's code/handlers/trackclients.q, built on the consolidated di.*
conventions (post-#128/#129). It records every inbound IPC/WebSocket session in a clients
table, optionally counts per-request hits and result bytes, and reaps idle connections.

  • init[config;deps] with settings under a `clienttracking section: enabled (1b),
    maxidle (0D - idle reaping off by default), retain (0D02:00:00), trackusage (1b).
    Defaults are TorQ's effective ones from config/settings/default.q. Absent section = defaults.
  • log and handlers are injected (required, strictly validated); no hard use deps, so no
    manifest - same as di.serverselect.
  • Every .z.* observer goes through di.torq.handlers. No direct .z.* assignment.
  • Exports: init, getclients, addclient, cleanup, enableusage, getapimeta, version.
  • Timespan settings accept the TOML string form ("0D00:15:00", "1D"); the D is mandatory -
    "900" is rejected rather than silently read as 9 hours.
  • enabled:0b on init (or re-init) unhooks every observer and watcher this module registered and
    stops, leaving the session table intact; a later enabled re-init puts everything back.

How it works

  • Session table - unkeyed clients (w ipa u a startp endp lastp hits sz) fed by simple
    observers on .z.po/.z.pc/.z.wo/.z.wc. Handle-number reuse closes the stale row on
    open, so there is never more than one open row per handle.
  • Usage counting - a post-phase watcher on .z.pg/.z.ps/.z.ws. It can only attach
    once that event has an exec owner; until then it is deferred (info log) and
    enableusage[] re-attaches it later. sz counts sync (.z.pg) results only - kdb+ discards
    the .z.ps/.z.ws return value, so measuring it would report bytes never sent.
  • cleanup - stamps endp on rows whose handle has left .z.W, force-closes handles idle
    past maxidle (never the caller's own handle), and drops closed rows older than retain.
    Idle reaping is suspended with a warning while usage counting is not live: lastp
    cannot advance without a post watcher, so every session would otherwise look idle and get
    reaped on the first sweep.
  • Hot path amends by name (.z.M.clients) rather than by value - measured 24× faster at 50k
    rows (3.4µs vs 83µs per request). Rationale and numbers are in the design-decisions section.

Testing

  • Unit - 123 checks, hermetic, recording handlers. Covers the init[config;deps] arity
    (a one-arg call silently returns a projection rather than erroring - pinned explicitly),
    config validation (types, string timespans, negative/null/infinite rejection), enabled/disabled
    init, deferred attach, hit/sz accounting on pg vs ps, handle reuse, retain expiry, the
    suspended-reap warning, and the getapimeta contract.
  • Integration - 18 checks, two legs. Inbound: a spawned child q hosts its own instance of
    the module with an exec owner, and this process is a genuine client of it - proves a real
    .z.po, hits on real requests, and the self-reap guard (calling cleanup[] over your own idle
    handle doesn't close it under you) on a real IPC round-trip. Outbound: this process tracks the
    handle to the child, proves idle reaping stays suspended with no exec owner here, then proves a
    real idle reap once one is registered. Skips cleanly if no q binary is found.
  • Both suites pass on KDB-X 0.1.2/2025.11.17 and 5.0/2026.07.23. qlint clean.
  • Smoke-tested independently over real tcp and unix-domain sockets, and against a full
    TorqX-POC stack (tp, hdb, rdb, wdb, gateway, feed) wired from code/common. Three bugs
    found in that pass are fixed here with regression tests: self-reap, duplicate rows on handle
    reuse, and the by-value table copy.

Run the unit suite:

q)k4unit:use`di.k4unit
q)k4unit.moduletest`di.clienttracking

The integration suite needs a fresh session (moduletest only loads test.csv):

q).m.di.0k4unit.KUltf .Q.dd[hsym`$.Q.m.mp`di.clienttracking;`test_integration.csv]
q).m.di.0k4unit.KUrt[]
q)k4unit.getresults[]

Known limitation - please read before reviewing

No di.torq process type currently claims exec on .z.pg/.z.ps. On a stock stack
that means usage counting stays deferred and idle reaping stays suspended (with a clear
warning) until a host registers an exec owner. Session tracking - the table, open/close
stamps, retain cleanup - is fully live regardless. The gate is tested in both suites and
documented; the fix belongs in di.torq, not here (see follow-up 1 - note that landing it
would also mean di.querylog's wrappers get displaced the moment something claims exec,
so the two need reconciling together, not just this module).

di.torq also has no settings-section hook for this module yet (the way di.querylog has);
a host wires it from app code as shown in the Initialisation section of the docs.

Follow-ups (separate PRs/issues, not in this change)

  1. di.torq / di.torq.handlers: a default exec owner on .z.pg/.z.ps. Root cause
    of the limitation above. Note that once anything claims exec via handlers, di.querylog's
    direct-assignment wrappers are displaced - the two need to be reconciled together.
  2. di.util.toml: two sections with different key sets throw 'mismatch. Found while
    feeding this module a real TOML config. Independent of this PR - worth filing/fixing
    promptly since it's already live on main, not just a design note.
  3. di/torq/handlers/handlers.md is stale - it doesn't mention the shipped transform
    phase, which this module's docs rely on to explain what post sees.

…ting

A kdb-x module for TorQ's code/handlers/trackclients.q on the consolidated di.*
conventions: init[config;deps] with settings under a `clienttracking section
(enabled, maxidle, retain, trackusage), log and handlers injected, every .z.*
observer registered through di.torq.handlers, no manifest (zero hard deps).

Behaviour:
- an unkeyed clients table (w, ipa, u, a, startp, endp, lastp, hits, sz) fed by
  simple observers on .z.po/.z.pc/.z.wo/.z.wc; getclients/addclient/cleanup
  exported plus getapimeta and version
- usage counting (hits/sz/lastp) as a post-phase watcher on .z.pg/.z.ps/.z.ws,
  attached only once an exec owner exists on that event, otherwise deferred
  (enableusage[] re-attaches later); sz measures sync (.z.pg) results only, as
  kdb+ discards the ps/ws return value
- cleanup[] stamps endp on rows whose handle has left .z.W, reaps idle handles
  past maxidle, and drops closed rows older than retain; idle reaping is
  suspended (with a warning) while usage counting is not live, because lastp
  cannot advance and every session would otherwise look idle
- timespan settings accept the TOML string form ("0D00:15:00", "1D"); the D is
  mandatory - "900" is rejected rather than read as 9 hours

Found and fixed during socket and TorqX-POC smoke testing, each with a test:
- cleanup could close the caller's own handle mid-request (w<>.z.w guard)
- a reused handle number left two open rows (the stale row is closed on .z.po)
- the clients update copied the whole table per request (amend by name via
  .z.M.clients; 24x faster at 50k rows)

Tests: 123 unit checks (hermetic, recording handlers) and 18 integration checks
that spawn a real child q hosting the module and drive it over IPC, proving the
self-reap guard, a genuine idle reap out of .z.W, and the no-exec-owner gate.
Both pass on KDB-X 0.1.2/2025.11.17 and 5.0/2026.07.23.

Known limitation, documented: no di.torq process type currently claims exec on
.z.pg/.z.ps, so on a stock stack usage counting stays deferred and idle reaping
suspended until a host wires an exec owner. Session tracking is unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread di/clienttracking/init.q Resolved
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

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

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

Suggestions

  • di/clienttracking/clienttracking.q:192 — In enableusage, the local lambda active is defined and immediately called with each usageevents on the same expression. The lambda closes over .z.m.handlers and handlerpriority, but handlerpriority is a module-level name that resolves at load time — that is fine. The real issue is: active is a named local variable inside enableusage, yet it is also a q built-in name (active is not reserved, so this is not a load-time break). More critically, the result of active:{...} each usageevents is a boolean list, and .z.m.usageactive:any active uses the local name active which holds the results list — but the lambda is also named active, so after {...} each usageevents runs, active is the result list (the lambda is shadowed by the assignment). This is correct as written since : owned inside the lambda does not assign to the outer active. However, this is fragile and confusing: rename the lambda (e.g. checkowner) to make the intent unambiguous.
  • di/clienttracking/clienttracking.q:160 — In cleanup, the idle-reap block uses exec w from .z.m.clients (value copy via .z.m) to collect idle handles, then does @[hclose;;::] each idle and update endp:now from .z.M.clients where w in idle,null endp. If hclose on one of the handles triggers a .z.pc callback (which calls closeclient, which calls cleanup again), the re-entrant cleanup will attempt to update endp on .z.M.clients while the outer call is mid-loop. q is single-threaded so the callbacks from hclose fire synchronously inline before hclose returns. This means the .z.pc handler fires for each closed handle during the each idle loop, each calling closeclient → cleanup → stamping endp again (no-op since null endp is false after the first stamp). The outer update endp … where w in idle,null endp then finds no matching rows (all already stamped). The net result is correct behaviour but the re-entrant cleanup also re-runs the hclose branch — at that point idle is re-computed from .z.m.clients where the handle just closed may already have endp stamped by the inner .z.pc→closeclient path, so it won't be double-closed. However the full re-entrant sweep (including the delete purge) runs redundantly for every hclose. More importantly, if .z.pc is NOT registered (e.g. enabled:0b was set after the handles were tracked), closeclient won't stamp endp, and the outer update will correctly stamp them in bulk. The logic is safe but the re-entrant sweep inside the each is an unintended side-effect; guard cleanup against re-entrancy with a flag.

A DIReview comment on clienttracking.q:94 (coercespan) flagged that retain:0D
and maxidle:0D are accepted by the same guard but mean different things:
maxidle:0D is an explicitly-gated disable value (cleanup's idle-reap branch
checks 0D<maxidle), but retain:0D has no equivalent gate - it flows straight
into `endp<now-retain`, which reduces to `endp<now` and purges essentially
every closed row on the very next sweep. So retain:0D means "purge closed
rows immediately", not "keep forever".

This is correct, existing behaviour, not a bug - the fix is documentation
plus a test pinning it, not a coercespan change:

- clienttracking.md: the retain row in the Configuration table now flags
  that 0D is not a keep-forever value, and a new paragraph next to the
  existing maxidle:0D note spells out the contrast and the endp<now-0D
  arithmetic explicitly.
- test.csv: a new block inits with retain:0D, opens and closes a synthetic
  handle, runs cleanup[], and asserts the closed row is gone - proving the
  documented behaviour rather than just asserting it in prose.

No change to clienttracking.q. Full suite green: 129/129 unit (was 123,
+6 for the new block), 18/18 integration, both on KDB-X 0.1.2/2025.11.17
and 5.0/2026.07.23.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@DI-Software-Engineering

Copy link
Copy Markdown

DIReview Summary

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

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

Suggestions

  • di/clienttracking/test.csv:119 — The test uses a hardcoded handle value w=8009i to verify the row was purged, but w is the OS-assigned file descriptor for the connection, not the port number. The .z.po / .z.pc calls on port 8009i will produce a w value assigned by the OS (typically a small integer like 5, 6, 7…), not 8009. The assertion 0=count select from ct.getclients[] where w=8009i will almost always return 1 (zero rows match 8009) regardless of whether the purge actually worked, making the test trivially pass even if the purge is broken. Fix by capturing the handle from .z.po into a variable and filtering on that, or by asserting 0=count select from ct.getclients[] where not null endp after the sweep.

@Papamaci444 Papamaci444 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Read all, tried the tests, looks good to me!

@alowrydi
alowrydi merged commit 478bfdd into main Sep 18, 2026
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