vouchington-tooling 0.76.0 → 0.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1337,6 +1337,13 @@ touching it. `tmux post-tool` reads an agent post-tool hook payload on stdin and
1337
1337
  reminder at plan, PR, push and reset checkpoints; reminders name `TMUX_NAME_COMMAND` (default
1338
1338
  `vouchington tmux name`).
1339
1339
 
1340
+ ## Worker query profiles
1341
+
1342
+ `vouchington-tooling/worker-query-profile` provides test-only worker profiling through the optional
1343
+ PostgreSQL and worker-runtime peers. It installs the runtime factory decorator and supplies a thin
1344
+ testing Worker adapter with per-instance observers. Profiles, violation collection, and diagnostic
1345
+ configuration are injected. See [worker query profile usage](docs/worker-query-profile.md).
1346
+
1340
1347
  ## Request query profiles
1341
1348
 
1342
1349
  `vouchington-tooling/request-query-profile` is the test-only rule layer on top of a per-request
@@ -0,0 +1,30 @@
1
+ import type { QueryProfiles, WorkerQueryProfile } from '@vouchington/postgres/query-telemetry';
2
+ import { Worker as SdkWorker, type WorkerOptions } from '@vouchington/worker-runtime/testing';
3
+ import { type WorkerProfileReporting } from './reporting.mts';
4
+ export type ProfileObserver = (profile: WorkerQueryProfile) => undefined;
5
+ export type WorkerProcessor<R = unknown> = (job: any) => R | Promise<R>;
6
+ export interface WorkerQueryProfileOptions extends WorkerProfileReporting {
7
+ profiles: Pick<QueryProfiles, 'runIndependentWorker'>;
8
+ identities?: (input: unknown) => {
9
+ id: string;
10
+ name: string;
11
+ }[];
12
+ }
13
+ export declare function workerQueryIdentities(input: unknown): {
14
+ id: string;
15
+ name: string;
16
+ }[];
17
+ export interface ProfiledWorker<D = unknown, R = unknown> extends SdkWorker<D, R> {
18
+ observeQueryProfiles(observer: ProfileObserver): () => void;
19
+ }
20
+ export interface WorkerQueryProfileHelpers {
21
+ Worker: Omit<typeof SdkWorker, 'prototype'> & {
22
+ readonly prototype: ProfiledWorker;
23
+ new <D = unknown, R = unknown>(queue: ConstructorParameters<typeof SdkWorker<D, R>>[0], processor: ConstructorParameters<typeof SdkWorker<D, R>>[1], options?: WorkerOptions<R>): ProfiledWorker<D, R>;
24
+ };
25
+ wrapProcessor<R>(processor: WorkerProcessor<R>, queue: string, observe?: ProfileObserver): (job: any) => Promise<R>;
26
+ wrapProcessor(processor: unknown, queue: string, observe?: ProfileObserver): WorkerProcessor;
27
+ install: () => () => void;
28
+ }
29
+ /** Test-only profiling instrumentation; business work stays in the SDK worker. */
30
+ export declare function createWorkerQueryProfileHelpers(options: WorkerQueryProfileOptions): WorkerQueryProfileHelpers;
@@ -0,0 +1,111 @@
1
+ import { Worker as SdkWorker, getTestWorkerProcessorDecorator, setTestWorkerProcessorDecorator, } from '@vouchington/worker-runtime/testing';
2
+ import { finishProfile, reportFailure } from "./reporting.mjs";
3
+ // Function identity, rather than queue identity, separates workers sharing a queue or processor.
4
+ // The global registry also recognizes factory decorators retained across module resets.
5
+ const metadataKey = Symbol.for('vouchington-tooling.worker-query-profile.metadata.v1');
6
+ const metadata = (globalThis[metadataKey] ??= new WeakMap());
7
+ export function workerQueryIdentities(input) {
8
+ const jobs = Array.isArray(input) ? input : [input];
9
+ if (!jobs.length)
10
+ throw new Error('Test worker profiles require every batch member identity');
11
+ return jobs.map((job) => {
12
+ if (!job ||
13
+ typeof job !== 'object' ||
14
+ !('id' in job) ||
15
+ !('name' in job) ||
16
+ typeof job.id !== 'string' ||
17
+ !job.id ||
18
+ typeof job.name !== 'string' ||
19
+ !job.name) {
20
+ throw new Error('Test worker profiles require every batch member identity');
21
+ }
22
+ return { id: job.id, name: job.name };
23
+ });
24
+ }
25
+ /** Test-only profiling instrumentation; business work stays in the SDK worker. */
26
+ export function createWorkerQueryProfileHelpers(options) {
27
+ function wrapProcessor(processor, queue, observe) {
28
+ if (typeof processor !== 'function') {
29
+ throw new TypeError('Test worker processor decorators require a function');
30
+ }
31
+ return decorate(processor, queue, new Set(), observe);
32
+ }
33
+ function decorate(base, queue, observers, observe) {
34
+ const wrapped = async (job) => {
35
+ const worker = options.profiles.runIndependentWorker({ queue, jobs: (options.identities ?? workerQueryIdentities)(job) }, () => Promise.resolve(base(job)), (profile) => {
36
+ // A snapshot defers observers added during delivery until the next profile.
37
+ // oxlint-disable-next-line unicorn/no-useless-spread
38
+ for (const observer of [...observers]) {
39
+ if (!observers.has(observer))
40
+ continue;
41
+ try {
42
+ observer(profile);
43
+ }
44
+ catch (error) {
45
+ reportFailure(profile, 'profile-observer', error, options);
46
+ }
47
+ }
48
+ observe?.(profile);
49
+ });
50
+ try {
51
+ return await worker.completion;
52
+ }
53
+ finally {
54
+ finishProfile(worker.profile, options);
55
+ }
56
+ };
57
+ metadata.set(wrapped, {
58
+ base,
59
+ observers,
60
+ rewrap: (processor, queue) => decorate(processor, queue, new Set(), observe),
61
+ });
62
+ return wrapped;
63
+ }
64
+ class Worker extends SdkWorker {
65
+ profileObservers;
66
+ constructor(queueNameOrQueue, processor, workerOptions) {
67
+ const queue = typeof queueNameOrQueue === 'string' ? queueNameOrQueue : queueNameOrQueue.name;
68
+ const existing = metadata.get(processor);
69
+ const { wrapProcessor: callerWrap, ...sdkOptions } = workerOptions ?? {};
70
+ const base = existing?.base ?? processor;
71
+ const callerWrapped = callerWrap?.(base, queue) ?? base;
72
+ const decorated = existing
73
+ ? existing.rewrap(callerWrapped, queue)
74
+ : wrapProcessor(callerWrapped, queue);
75
+ const observers = metadata.get(decorated).observers;
76
+ super(queueNameOrQueue, decorated, sdkOptions);
77
+ this.profileObservers = observers;
78
+ }
79
+ observeQueryProfiles(observer) {
80
+ this.profileObservers.add(observer);
81
+ return () => {
82
+ this.profileObservers.delete(observer);
83
+ };
84
+ }
85
+ }
86
+ let installations = 0;
87
+ let restoreInstallation;
88
+ function install() {
89
+ if (installations === 0) {
90
+ const previous = getTestWorkerProcessorDecorator();
91
+ const installed = previous
92
+ ? (processor, queue) => wrapProcessor(previous(processor, queue), queue)
93
+ : wrapProcessor;
94
+ setTestWorkerProcessorDecorator(installed);
95
+ restoreInstallation = () => {
96
+ if (getTestWorkerProcessorDecorator() === installed)
97
+ setTestWorkerProcessorDecorator(previous);
98
+ };
99
+ }
100
+ installations++;
101
+ let active = true;
102
+ return () => {
103
+ if (!active)
104
+ return;
105
+ active = false;
106
+ if (--installations === 0)
107
+ restoreInstallation();
108
+ };
109
+ }
110
+ return { Worker, wrapProcessor, install };
111
+ }
@@ -0,0 +1,9 @@
1
+ import type { WorkerQueryProfile } from '@vouchington/postgres/query-telemetry';
2
+ export interface WorkerProfileReporting {
3
+ recordViolation: (message: string) => void;
4
+ recordKind: string;
5
+ diagnosticsEnvVar: string;
6
+ output?: (line: string) => void;
7
+ }
8
+ export declare function reportFailure(profile: WorkerQueryProfile, stage: string, error: unknown, options: WorkerProfileReporting): void;
9
+ export declare function finishProfile(profile: WorkerQueryProfile, options: WorkerProfileReporting): void;
@@ -0,0 +1,38 @@
1
+ function publishViolation(profile, options) {
2
+ try {
3
+ options.recordViolation('Independent worker query profile reporting failed');
4
+ }
5
+ catch (error) {
6
+ profile.reportFailure('violation-collector', error);
7
+ }
8
+ }
9
+ export function reportFailure(profile, stage, error, options) {
10
+ profile.reportFailure(stage, error);
11
+ publishViolation(profile, options);
12
+ }
13
+ function snapshot(profile) {
14
+ return {
15
+ identity: profile.identity,
16
+ queries: profile.queries(),
17
+ summary: profile.summarize(),
18
+ reportingFailureStages: profile.reportingFailures().map((failure) => failure.stage),
19
+ children: profile.workerProfiles().map(snapshot),
20
+ };
21
+ }
22
+ export function finishProfile(profile, options) {
23
+ if (profile.reportingFailures().some((failure) => failure.stage.startsWith('profile-owner'))) {
24
+ publishViolation(profile, options);
25
+ }
26
+ try {
27
+ if (process.env[options.diagnosticsEnvVar] !== '1' && !profile.reportingFailures().length)
28
+ return;
29
+ const line = `${JSON.stringify({ kind: options.recordKind, pid: process.pid, profile: snapshot(profile) })}\n`;
30
+ if (options.output)
31
+ options.output(line);
32
+ else
33
+ process.stderr.write(line);
34
+ }
35
+ catch (error) {
36
+ reportFailure(profile, 'profile-output', error, options);
37
+ }
38
+ }
@@ -0,0 +1,46 @@
1
+ # Worker query profiles in tests
2
+
3
+ The `worker-query-profile` subpath supplies test instrumentation over the public PostgreSQL query
4
+ profiles and worker-runtime testing APIs. Install the optional peer packages when using it.
5
+
6
+ ```ts
7
+ import { createQueryProfiles } from '@vouchington/postgres/query-telemetry'
8
+ import { createWorkerQueryProfileHelpers } from 'vouchington-tooling/worker-query-profile'
9
+
10
+ const profiles = createQueryProfiles()
11
+ const helpers = createWorkerQueryProfileHelpers({
12
+ profiles,
13
+ recordViolation: (message) => violations.push(message),
14
+ recordKind: 'test-worker',
15
+ diagnosticsEnvVar: 'TEST_QUERY_DIAGNOSTICS',
16
+ })
17
+ const restore = helpers.install()
18
+ ```
19
+
20
+ `install()` composes the existing global test processor decorator inside the profiling decorator.
21
+ SDK runtime factories then profile single and batch processors. Its cleanup restores the previous
22
+ decorator only while the installed decorator still owns the global slot. Repeated installs from
23
+ the same helpers share one decorator; their idempotent cleanup functions release it when the last
24
+ installation is released.
25
+
26
+ `helpers.wrapProcessor(processor, queue, observer?)` also profiles a standalone processor. Its
27
+ optional owner observer is preserved when the processor is adapted into a Worker. Owner failures
28
+ are captured by the SDK without suppressing instance observers or replacing the business outcome.
29
+
30
+ Use `helpers.Worker` as the testing Worker adapter for direct construction or the test alias of the
31
+ factory's Worker import. It delegates execution, scheduling, options, and lifecycle to the SDK. Each
32
+ worker offers `observeQueryProfiles(observer)`, returning an unsubscribe function. The observer must
33
+ return `undefined`; asynchronous observers are unsupported. Factory-decorated processors retain
34
+ their original profile owner, even after module resets, without a second profiling scope. Caller
35
+ processor wrappers run inside profile collection. Distinct decorated processors keep separate
36
+ observers even when their queue and business processor are shared.
37
+
38
+ By default every job must have a nonempty string `id` and `name`; a batch must be nonempty and all
39
+ members must pass validation before business work starts. Supply `identities` for a different input
40
+ shape. This callback must return complete job identities or throw before invocation.
41
+
42
+ Diagnostics are emitted as one JSON line when the configured environment variable equals `1`, or
43
+ when reporting failures occur. `output` can replace stderr. Observer and output failures are
44
+ recorded on the profile and sent to the injected violation collector. A failed collector is recorded
45
+ as another reporting failure. Reporting preserves business results and errors. Consumers own the
46
+ collector and choose when accumulated violations fail their tests.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.76.0",
3
+ "version": "0.78.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -481,6 +481,11 @@
481
481
  "types": "./dist/input-otp-mock/index.d.mts",
482
482
  "import": "./dist/input-otp-mock/index.mjs",
483
483
  "default": "./dist/input-otp-mock/index.mjs"
484
+ },
485
+ "./worker-query-profile": {
486
+ "types": "./dist/worker-query-profile/index.d.mts",
487
+ "import": "./dist/worker-query-profile/index.mjs",
488
+ "default": "./dist/worker-query-profile/index.mjs"
484
489
  }
485
490
  },
486
491
  "publishConfig": {
@@ -516,6 +521,9 @@
516
521
  "@types/react": "19.3.0",
517
522
  "@types/react-dom": "19.3.0",
518
523
  "@types/spdx-expression-parse": "4.0.0",
524
+ "@vouchington/postgres": "0.1.0",
525
+ "@vouchington/worker-runtime": "0.2.1",
526
+ "glide-mq": "^0.19.0",
519
527
  "next": "16.4.2",
520
528
  "no-mistakes": "0.83.0",
521
529
  "pg": "8.23.1",
@@ -527,6 +535,8 @@
527
535
  "peerDependencies": {
528
536
  "@modelcontextprotocol/sdk": "^1.31.0",
529
537
  "@playwright/test": ">=1.64.1",
538
+ "@vouchington/postgres": ">=0.1.0",
539
+ "@vouchington/worker-runtime": ">=0.2.1",
530
540
  "next": ">=15",
531
541
  "no-mistakes": "*",
532
542
  "pg": ">=8",
@@ -558,6 +568,12 @@
558
568
  },
559
569
  "vitest": {
560
570
  "optional": true
571
+ },
572
+ "@vouchington/postgres": {
573
+ "optional": true
574
+ },
575
+ "@vouchington/worker-runtime": {
576
+ "optional": true
561
577
  }
562
578
  },
563
579
  "optionalDependencies": {
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ // Browser builds follow the single playwright-core version in the lockfile.
4
+ // Callers key the browser cache on that version instead of the whole lockfile.
5
+ const lockfilePath = process.argv[2] ?? 'pnpm-lock.yaml'
6
+
7
+ let source
8
+ try {
9
+ source = readFileSync(lockfilePath, 'utf8')
10
+ } catch {
11
+ process.stderr.write(`::error::cannot read ${lockfilePath}\n`)
12
+ process.exit(2)
13
+ }
14
+
15
+ if (!/^lockfileVersion:\s+['"]?9\.\d+['"]?\s*$/m.test(source)) {
16
+ process.stderr.write('::error::pnpm-lock.yaml must use lockfileVersion 9\n')
17
+ process.exit(2)
18
+ }
19
+
20
+ const versions = new Set()
21
+ for (const line of source.split('\n')) {
22
+ const match = /^ {2}['"]?playwright-core@([^'"\n:]+)['"]?(?::(?: \{\})?)?$/.exec(line)
23
+ if (!match) continue
24
+ const version = match[1].split('(')[0]
25
+ if (!/^\d+\.\d+\.\d+$/.test(version)) {
26
+ process.stderr.write(`::error::playwright-core version ${version} is not numeric x.y.z\n`)
27
+ process.exit(2)
28
+ }
29
+ versions.add(version)
30
+ }
31
+
32
+ if (versions.size !== 1) {
33
+ process.stderr.write(
34
+ `::error::expected one playwright-core version in the lockfile, found ${versions.size}\n`,
35
+ )
36
+ process.exit(2)
37
+ }
38
+
39
+ process.stdout.write(`${[...versions][0]}\n`)