From 2e9f8cc2b84c992e880174f204cf47f8c3bac97f Mon Sep 17 00:00:00 2001 From: Thomas Hardy Date: Fri, 2 Oct 2026 09:46:07 -0400 Subject: [PATCH 1/6] test: restore Runtime shutdown assertions in worker lifecycle tests Use Worker-owned connections built from envconfig instead of the shared test environment, whose connections keep the Runtime alive, so the tests again assert that the Runtime shuts down when the last Worker stops. Co-Authored-By: Claude Opus 5.5 --- .../src/test-worker-lifecycle-integration.ts | 207 ++++++++++-------- 1 file changed, 115 insertions(+), 92 deletions(-) diff --git a/packages/test/src/test-worker-lifecycle-integration.ts b/packages/test/src/test-worker-lifecycle-integration.ts index 091b372cd3..66cba62245 100644 --- a/packages/test/src/test-worker-lifecycle-integration.ts +++ b/packages/test/src/test-worker-lifecycle-integration.ts @@ -1,106 +1,129 @@ -/** Worker lifecycle integration tests. */ +/** + * Worker lifecycle integration tests. + * + * These tests deliberately avoid a shared test environment: each Worker owns its connection, so the + * Runtime shuts down once the last Worker stops, exactly as it does for a Worker created without one. + */ import { randomUUID } from 'crypto'; import { setTimeout } from 'timers/promises'; +import test from 'ava'; +import { Client, Connection } from '@temporalio/client'; +import { loadClientConnectConfig } from '@temporalio/envconfig'; +import type { WorkerOptions } from '@temporalio/worker'; import { PromiseCompletionTimeoutError, Runtime, TransportError, UnexpectedError } from '@temporalio/worker'; -import { isBun } from './helpers'; -import { helpers, makeTestFunction } from './helpers-integration'; +import { InternalNativeConnection } from '@temporalio/worker/lib/connection'; +import { isBun, RUN_INTEGRATION_TESTS, Worker } from './helpers'; +import { defaultOptions } from './mock-native-worker'; import { fillMemory } from './workflows'; -const test = makeTestFunction({ workflowsPath: require.resolve('./workflows') }); +const { namespace, connectionOptions } = loadClientConnectConfig(); -// The shared TestWorkflowEnvironment keeps its native connections alive until the suite teardown, -// so these tests verify Worker shutdown without expecting Runtime._instance to clear per test. +/** + * Create a Worker on a configured connection that the Worker owns and closes when it shuts down. + */ +async function createWorker(options: Partial & Pick) { + const connection = await InternalNativeConnection.connect(connectionOptions); + try { + return await Worker.create({ ...defaultOptions, connection, namespace, ...options }); + } catch (err) { + await connection.close(); + throw err; + } +} -test.serial('Worker shuts down gracefully', async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.is(worker.getState(), 'INITIALIZED'); - t.not(Runtime._instance, undefined); - const workerRun = worker.run(); - t.is(worker.getState(), 'RUNNING'); - process.emit('SIGINT', 'SIGINT'); - await new Promise((resolve) => process.nextTick(resolve)); - t.is(worker.getState(), 'DRAINING'); - await workerRun; - t.is(worker.getState(), 'STOPPED'); - await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); -}); +if (RUN_INTEGRATION_TESTS) { + test.serial('Worker shuts down gracefully', async (t) => { + const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + t.is(worker.getState(), 'INITIALIZED'); + t.not(Runtime._instance, undefined); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + process.emit('SIGINT', 'SIGINT'); + await new Promise((resolve) => process.nextTick(resolve)); + t.is(worker.getState(), 'DRAINING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); + t.is(Runtime._instance, undefined); + }); -test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.not(Runtime._instance, undefined); - const p = worker.runUntil( - new Promise(() => { - // A promise that will never unblock. - }) - ); - t.is(worker.getState(), 'RUNNING'); - worker.shutdown(); - t.is(worker.getState(), 'DRAINING'); - await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); - t.is(worker.getState(), 'STOPPED'); -}); + test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { + const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + t.not(Runtime._instance, undefined); + const p = worker.runUntil( + new Promise(() => { + // A promise that will never unblock. + }) + ); + t.is(worker.getState(), 'RUNNING'); + worker.shutdown(); + t.is(worker.getState(), 'DRAINING'); + await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); + t.is(worker.getState(), 'STOPPED'); + t.is(Runtime._instance, undefined); + }); -test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.is(worker.getState(), 'INITIALIZED'); - process.emit('SIGINT', 'SIGINT'); - const workerRun = worker.run(); - t.is(worker.getState(), 'RUNNING'); - await workerRun; - t.is(worker.getState(), 'STOPPED'); -}); + test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { + const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + t.is(worker.getState(), 'INITIALIZED'); + process.emit('SIGINT', 'SIGINT'); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + }); -test.serial('Worker fails validation against unknown namespace', async (t) => { - const { createWorker } = helpers(t); - await t.throwsAsync( - createWorker({ - namespace: 'oogabooga', - }), - { - // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. - instanceOf: TransportError, - // Cloud credentials cannot describe namespaces outside their authorized scope. - message: /Namespace oogabooga (?:is not found|was not found or otherwise could not be described)/, - } - ); -}); + test.serial('Worker fails validation against unknown namespace', async (t) => { + await t.throwsAsync( + createWorker({ + taskQueue: t.title.replace(/ /g, '_'), + namespace: 'oogabooga', + }), + { + // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. + instanceOf: TransportError, + // Cloud credentials cannot describe namespaces outside their authorized scope. + message: /Namespace oogabooga (?:is not found|was not found or otherwise could not be described)/, + } + ); + }); -(isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { - t.timeout(30_000); - const { taskQueue, createWorker } = helpers(t); - const client = t.context.env.client; - const worker = await createWorker(); + (isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { + t.timeout(30_000); + const taskQueue = t.title.replace(/ /g, '_'); + const connection = await Connection.connect(connectionOptions); + const client = new Client({ connection, namespace }); + const worker = await createWorker({ taskQueue }); - client.workflow - .start(fillMemory, { - taskQueue, - workflowId: randomUUID(), - workflowExecutionTimeout: '30s', - }) - .catch(() => void 0); + client.workflow + .start(fillMemory, { + taskQueue, + workflowId: randomUUID(), + workflowExecutionTimeout: '30s', + }) + .catch(() => void 0); - const workerRun = worker.run(); - try { - await Promise.race([setTimeout(10_000), workerRun]); - if (worker.getState() === 'RUNNING') { - worker.shutdown(); - await workerRun; + const workerRun = worker.run(); + try { + await Promise.race([setTimeout(10_000), workerRun]); + if (worker.getState() === 'RUNNING') { + worker.shutdown(); + await workerRun; + } + t.log('Non-conclusive result: Worker did not fail as expected'); + t.pass(); + } catch (err) { + // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. + t.is((err as Error).name, UnexpectedError.name); + t.is( + (err as Error).message, + 'Workflow Worker Thread exited prematurely: Error [ERR_WORKER_OUT_OF_MEMORY]: ' + + 'Worker terminated due to reaching memory limit: JS heap out of memory' + ); + t.is(worker.getState(), 'FAILED'); + } finally { + await connection.close(); + if (Runtime._instance) await Runtime._instance.shutdown(); } - t.log('Non-conclusive result: Worker did not fail as expected'); - t.pass(); - } catch (err) { - // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. - t.is((err as Error).name, UnexpectedError.name); - t.is( - (err as Error).message, - 'Workflow Worker Thread exited prematurely: Error [ERR_WORKER_OUT_OF_MEMORY]: ' + - 'Worker terminated due to reaching memory limit: JS heap out of memory' - ); - t.is(worker.getState(), 'FAILED'); - } finally { - if (Runtime._instance) await Runtime._instance.shutdown(); - } -}); + }); +} From 87717046376f6b52b945764898a5017c235baad8 Mon Sep 17 00:00:00 2001 From: Thomas Hardy Date: Tue, 13 Oct 2026 11:54:38 -0400 Subject: [PATCH 2/6] test: share an owned-connection Worker helper for Runtime lifecycle tests Tests that assert Runtime teardown need each Worker to own its connection, so the Runtime shuts down once the last Worker stops; a shared test environment keeps it alive. Move that helper into helpers.ts, choosing the server like createTestWorkflowEnvironment() does (envconfig only when TEMPORAL_TEST_ENV_CONFIG_SERVER is set, otherwise TEMPORAL_SERVICE_ADDRESS or the default local address) instead of always reading a local envconfig profile. Also give lifecycle tests unique task queues, since a namespace may be shared. Co-Authored-By: Claude Opus 5.5 --- packages/test/src/helpers.ts | 45 +++++++++++++++++++ .../src/test-worker-lifecycle-integration.ts | 35 +++++++-------- 2 files changed, 60 insertions(+), 20 deletions(-) diff --git a/packages/test/src/helpers.ts b/packages/test/src/helpers.ts index d18462d12d..6906a1de5a 100644 --- a/packages/test/src/helpers.ts +++ b/packages/test/src/helpers.ts @@ -4,9 +4,14 @@ import * as grpc from '@grpc/grpc-js'; import asyncRetry from 'async-retry'; import type { Connection } from '@temporalio/client'; import { Client } from '@temporalio/client'; +import { loadClientConnectConfig } from '@temporalio/envconfig'; +import type { NativeConnectionOptions, WorkerOptions } from '@temporalio/worker'; +import { InternalNativeConnection } from '@temporalio/worker/lib/connection'; import * as iface from '@temporalio/proto'; import { createBaseBundlerOptions, + isSet, + Worker, loadHistory as loadHistoryBase, saveHistory as saveHistoryBase, RUN_TIME_SKIPPING_TESTS, @@ -47,6 +52,46 @@ export const bundlerOptions = createBaseBundlerOptions([ require.resolve('./mock-native-worker'), ]); +/** + * Server connection settings for tests that must own their connections instead of using a shared test environment. + * + * Chosen like `createTestWorkflowEnvironment()`, but never starts a server: envconfig when + * `TEMPORAL_TEST_ENV_CONFIG_SERVER` is set (e.g. on Cloud), otherwise `TEMPORAL_SERVICE_ADDRESS` or the default + * local address, in the `default` namespace. + */ +export function ownedConnectionConfig(): { namespace: string; connectionOptions: NativeConnectionOptions } { + if (isSet(process.env.TEMPORAL_TEST_ENV_CONFIG_SERVER, false)) { + const { namespace, connectionOptions } = loadClientConnectConfig(); + return { namespace: namespace ?? 'default', connectionOptions }; + } + return { namespace: 'default', connectionOptions: { address: process.env.TEMPORAL_SERVICE_ADDRESS } }; +} + +/** + * Create a Worker on a connection that the Worker owns and closes when it shuts down. + * + * Once the last such Worker stops, the Runtime shuts down too; a shared test environment would keep it alive. + */ +export async function createWorkerWithOwnConnection( + options: Omit & Partial> +): ReturnType { + const { namespace, connectionOptions } = ownedConnectionConfig(); + const connection = await InternalNativeConnection.connect(connectionOptions); + try { + return await Worker.create({ connection, namespace, ...options }); + } catch (err) { + await connection.close(); + throw err; + } +} + +/** + * A task queue name unique to this test run, so tests sharing a server or namespace never poll each other's tasks. + */ +export function uniqueTaskQueue(title: string): string { + return `${title.replace(/[^a-zA-Z0-9]+/g, '-')}-${randomUUID()}`; +} + // Some of our tests expect "default custom search attributes" to exists, which used to be the case // in all deployment with support for advanced visibility. However, this might no longer be true in // some environement (e.g. Temporal CLI). Use the operator service to create them if they're missing. diff --git a/packages/test/src/test-worker-lifecycle-integration.ts b/packages/test/src/test-worker-lifecycle-integration.ts index 66cba62245..15b07e7d3a 100644 --- a/packages/test/src/test-worker-lifecycle-integration.ts +++ b/packages/test/src/test-worker-lifecycle-integration.ts @@ -8,32 +8,27 @@ import { randomUUID } from 'crypto'; import { setTimeout } from 'timers/promises'; import test from 'ava'; import { Client, Connection } from '@temporalio/client'; -import { loadClientConnectConfig } from '@temporalio/envconfig'; import type { WorkerOptions } from '@temporalio/worker'; import { PromiseCompletionTimeoutError, Runtime, TransportError, UnexpectedError } from '@temporalio/worker'; -import { InternalNativeConnection } from '@temporalio/worker/lib/connection'; -import { isBun, RUN_INTEGRATION_TESTS, Worker } from './helpers'; +import { + createWorkerWithOwnConnection, + isBun, + ownedConnectionConfig, + RUN_INTEGRATION_TESTS, + uniqueTaskQueue, +} from './helpers'; import { defaultOptions } from './mock-native-worker'; import { fillMemory } from './workflows'; -const { namespace, connectionOptions } = loadClientConnectConfig(); +const { namespace, connectionOptions } = ownedConnectionConfig(); -/** - * Create a Worker on a configured connection that the Worker owns and closes when it shuts down. - */ -async function createWorker(options: Partial & Pick) { - const connection = await InternalNativeConnection.connect(connectionOptions); - try { - return await Worker.create({ ...defaultOptions, connection, namespace, ...options }); - } catch (err) { - await connection.close(); - throw err; - } +function createWorker(options: Partial & Pick) { + return createWorkerWithOwnConnection({ ...defaultOptions, ...options }); } if (RUN_INTEGRATION_TESTS) { test.serial('Worker shuts down gracefully', async (t) => { - const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); t.not(Runtime._instance, undefined); const workerRun = worker.run(); @@ -48,7 +43,7 @@ if (RUN_INTEGRATION_TESTS) { }); test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { - const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.not(Runtime._instance, undefined); const p = worker.runUntil( new Promise(() => { @@ -64,7 +59,7 @@ if (RUN_INTEGRATION_TESTS) { }); test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { - const worker = await createWorker({ taskQueue: t.title.replace(/ /g, '_') }); + const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); process.emit('SIGINT', 'SIGINT'); const workerRun = worker.run(); @@ -76,7 +71,7 @@ if (RUN_INTEGRATION_TESTS) { test.serial('Worker fails validation against unknown namespace', async (t) => { await t.throwsAsync( createWorker({ - taskQueue: t.title.replace(/ /g, '_'), + taskQueue: uniqueTaskQueue(t.title), namespace: 'oogabooga', }), { @@ -90,7 +85,7 @@ if (RUN_INTEGRATION_TESTS) { (isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { t.timeout(30_000); - const taskQueue = t.title.replace(/ /g, '_'); + const taskQueue = uniqueTaskQueue(t.title); const connection = await Connection.connect(connectionOptions); const client = new Client({ connection, namespace }); const worker = await createWorker({ taskQueue }); From 21b928d7302197b5b3d746f6a1fd5801d9415ada Mon Sep 17 00:00:00 2001 From: Thomas Hardy Date: Tue, 13 Oct 2026 11:54:38 -0400 Subject: [PATCH 3/6] test: adapt Runtime integration tests for Cloud The Runtime integration tests connected implicitly to localhost and the default namespace. Use Workers that own configured connections (through the shared helper) and clients on the same configured server, so the Runtime still shuts down and restarts as the tests expect. Replace the fixed `q1`/`q2` task queues with unique ones. Renamed to test-runtime-integration.ts, since test-runtime.ts already exists. Co-Authored-By: Claude Opus 5.5 --- ...pending.ts => test-runtime-integration.ts} | 67 ++++++++++++++----- 1 file changed, 49 insertions(+), 18 deletions(-) rename packages/test/src/{test-runtime.cloud-pending.ts => test-runtime-integration.ts} (62%) diff --git a/packages/test/src/test-runtime.cloud-pending.ts b/packages/test/src/test-runtime-integration.ts similarity index 62% rename from packages/test/src/test-runtime.cloud-pending.ts rename to packages/test/src/test-runtime-integration.ts index c7070637d8..691e0ac48c 100644 --- a/packages/test/src/test-runtime.cloud-pending.ts +++ b/packages/test/src/test-runtime-integration.ts @@ -1,35 +1,62 @@ /** - * Runtime integration tests that still construct implicit localhost clients and Workers. - * Tests run serially because Runtime is a singleton. + * Runtime integration tests. Tests run serially because Runtime is a singleton. + * + * These tests deliberately avoid a shared test environment, whose connections would keep the Runtime + * alive: each Worker owns its connection, so the Runtime shuts down once the last Worker stops. */ import { randomUUID } from 'crypto'; import asyncRetry from 'async-retry'; -import { Client, WorkflowClient } from '@temporalio/client'; -import type { LogEntry } from '@temporalio/worker'; +import type { ExecutionContext } from 'ava'; +import { Client, Connection, WorkflowClient } from '@temporalio/client'; +import type { LogEntry, WorkerOptions } from '@temporalio/worker'; import { DefaultLogger, makeTelemetryFilterString, NativeConnection, Runtime } from '@temporalio/worker'; -import { RUN_INTEGRATION_TESTS, test, Worker } from './helpers'; +import { + createWorkerWithOwnConnection, + ownedConnectionConfig, + RUN_INTEGRATION_TESTS, + test, + uniqueTaskQueue, + Worker, +} from './helpers'; import { createTestWorkflowBundle } from './helpers-integration'; import { defaultOptions } from './mock-native-worker'; import * as workflows from './workflows'; import { log5Times } from './workflows/runtime'; +const { namespace, connectionOptions } = ownedConnectionConfig(); + +function createWorker(options: Partial & Pick) { + return createWorkerWithOwnConnection({ ...defaultOptions, ...options }); +} + +/** + * Connect a client that is not tracked by the Runtime, closed when the test ends. + */ +async function connectClient(t: ExecutionContext): Promise { + const connection = await Connection.connect(connectionOptions); + t.teardown(() => connection.close()); + return connection; +} + if (RUN_INTEGRATION_TESTS) { test.serial('Runtime tracks registered workers, shuts down and restarts as expected', async (t) => { - const worker1 = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); - const worker2 = await Worker.create({ ...defaultOptions, taskQueue: 'q2' }); + const taskQueue1 = uniqueTaskQueue(`${t.title} 1`); + const taskQueue2 = uniqueTaskQueue(`${t.title} 2`); + const worker1 = await createWorker({ taskQueue: taskQueue1 }); + const worker2 = await createWorker({ taskQueue: taskQueue2 }); const worker1Drained = worker1.run(); const worker2Drained = worker2.run(); worker1.shutdown(); await worker1Drained; - const client = new WorkflowClient(); - await client.execute(workflows.sleeper, { taskQueue: 'q2', workflowId: randomUUID(), args: [1] }); + const client = new WorkflowClient({ connection: await connectClient(t), namespace }); + await client.execute(workflows.sleeper, { taskQueue: taskQueue2, workflowId: randomUUID(), args: [1] }); worker2.shutdown(); await worker2Drained; - const worker3 = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); + const worker3 = await createWorker({ taskQueue: taskQueue1 }); const worker3Drained = worker3.run(); - await client.execute('sleeper', { taskQueue: 'q1', workflowId: randomUUID(), args: [1] }); + await client.execute('sleeper', { taskQueue: taskQueue1, workflowId: randomUUID(), args: [1] }); worker3.shutdown(); await worker3Drained; t.pass(); @@ -45,7 +72,7 @@ if (RUN_INTEGRATION_TESTS) { t.true(messages.includes('before shutdown')); } - const worker = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); + const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); const workerDrained = worker.run(); worker.shutdown(); await workerDrained; @@ -66,8 +93,10 @@ if (RUN_INTEGRATION_TESTS) { telemetryOptions: { logging: { forward: {}, filter: makeTelemetryFilterString({ core: 'DEBUG' }) } }, }); try { - await new Client().workflow.start('not-existant', { taskQueue: 'q1', workflowId: randomUUID() }); - const worker = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); + const taskQueue = uniqueTaskQueue(t.title); + const client = new Client({ connection: await connectClient(t), namespace }); + await client.workflow.start('not-existant', { taskQueue, workflowId: randomUUID() }); + const worker = await createWorker({ taskQueue }); await worker.runUntil(() => asyncRetry( () => { @@ -80,11 +109,11 @@ if (RUN_INTEGRATION_TESTS) { const initWorkerEntry = logEntries.filter((x) => x.message === 'Initializing worker')?.[0]; t.true(initWorkerEntry !== undefined); - t.is(initWorkerEntry.meta?.['taskQueue'], 'q1'); + t.is(initWorkerEntry.meta?.['taskQueue'], taskQueue); const failingWftEntry = logEntries.filter((x) => x.message === 'Failing workflow task')?.[0]; t.true(failingWftEntry !== undefined); - t.is(failingWftEntry.meta?.['taskQueue'], 'q1'); + t.is(failingWftEntry.meta?.['taskQueue'], taskQueue); t.is(typeof failingWftEntry.meta?.['completion'], 'string'); t.is(typeof failingWftEntry.meta?.['failure'], 'string'); t.is(typeof failingWftEntry.meta?.['runId'], 'string'); @@ -104,19 +133,21 @@ if (RUN_INTEGRATION_TESTS) { }, }); const bufferedLogger = runtime.logger; - const connection = await NativeConnection.connect(); + const connection = await NativeConnection.connect(connectionOptions); try { const taskQueue = `runtime-native-log-collector-preriodically-flushed-${randomUUID()}`; const worker = await Worker.create({ ...defaultOptions, connection, + namespace, taskQueue, workflowBundle: await createTestWorkflowBundle({ workflowsPath: require.resolve('./workflows/runtime') }), }); + const client = new Client({ connection: await connectClient(t), namespace }); await worker.runUntil(async () => { - await new Client().workflow.execute(log5Times, { taskQueue, workflowId: randomUUID() }); + await client.workflow.execute(log5Times, { taskQueue, workflowId: randomUUID() }); }); t.true(logEntries.some((x) => x.message.startsWith('workflow log '))); From 51b996a1193a73bc05ead32e40cfb653004c411a Mon Sep 17 00:00:00 2001 From: Chris Olszewski Date: Mon, 9 Nov 2026 12:09:45 -0500 Subject: [PATCH 4/6] chore: avoid relying on internals --- packages/test/package.json | 1 + packages/test/src/helpers.ts | 21 +++--- packages/test/src/test-runtime-integration.ts | 59 ++++++++++------- .../src/test-worker-lifecycle-integration.ts | 64 +++++++++++++------ .../src/test-worker-owned-connection.local.ts | 63 ++++++++++++++++++ pnpm-lock.yaml | 3 + 6 files changed, 160 insertions(+), 51 deletions(-) create mode 100644 packages/test/src/test-worker-owned-connection.local.ts diff --git a/packages/test/package.json b/packages/test/package.json index 6cdabc78e4..bc4fceee61 100644 --- a/packages/test/package.json +++ b/packages/test/package.json @@ -38,6 +38,7 @@ "@temporalio/cloud": "workspace:*", "@temporalio/common": "workspace:*", "@temporalio/core-bridge": "workspace:*", + "@temporalio/envconfig": "workspace:*", "@temporalio/interceptors-opentelemetry": "workspace:*", "@temporalio/nexus": "workspace:*", "@temporalio/nyc-test-coverage": "workspace:*", diff --git a/packages/test/src/helpers.ts b/packages/test/src/helpers.ts index 6906a1de5a..c4b65093a8 100644 --- a/packages/test/src/helpers.ts +++ b/packages/test/src/helpers.ts @@ -6,7 +6,7 @@ import type { Connection } from '@temporalio/client'; import { Client } from '@temporalio/client'; import { loadClientConnectConfig } from '@temporalio/envconfig'; import type { NativeConnectionOptions, WorkerOptions } from '@temporalio/worker'; -import { InternalNativeConnection } from '@temporalio/worker/lib/connection'; +import { NativeConnection } from '@temporalio/worker'; import * as iface from '@temporalio/proto'; import { createBaseBundlerOptions, @@ -53,13 +53,13 @@ export const bundlerOptions = createBaseBundlerOptions([ ]); /** - * Server connection settings for tests that must own their connections instead of using a shared test environment. + * Server connection settings for tests that manage connections outside a shared test environment. * * Chosen like `createTestWorkflowEnvironment()`, but never starts a server: envconfig when * `TEMPORAL_TEST_ENV_CONFIG_SERVER` is set (e.g. on Cloud), otherwise `TEMPORAL_SERVICE_ADDRESS` or the default * local address, in the `default` namespace. */ -export function ownedConnectionConfig(): { namespace: string; connectionOptions: NativeConnectionOptions } { +export function configuredConnectionOptions(): { namespace: string; connectionOptions: NativeConnectionOptions } { if (isSet(process.env.TEMPORAL_TEST_ENV_CONFIG_SERVER, false)) { const { namespace, connectionOptions } = loadClientConnectConfig(); return { namespace: namespace ?? 'default', connectionOptions }; @@ -68,17 +68,16 @@ export function ownedConnectionConfig(): { namespace: string; connectionOptions: } /** - * Create a Worker on a connection that the Worker owns and closes when it shuts down. - * - * Once the last such Worker stops, the Runtime shuts down too; a shared test environment would keep it alive. + * Create a Worker with a dedicated connection that the caller must close after the Worker stops. */ -export async function createWorkerWithOwnConnection( +export async function createWorkerWithConnection( options: Omit & Partial> -): ReturnType { - const { namespace, connectionOptions } = ownedConnectionConfig(); - const connection = await InternalNativeConnection.connect(connectionOptions); +): Promise<{ worker: Awaited>; connection: NativeConnection }> { + const { namespace, connectionOptions } = configuredConnectionOptions(); + const connection = await NativeConnection.connect(connectionOptions); try { - return await Worker.create({ connection, namespace, ...options }); + const worker = await Worker.create({ connection, namespace, ...options }); + return { worker, connection }; } catch (err) { await connection.close(); throw err; diff --git a/packages/test/src/test-runtime-integration.ts b/packages/test/src/test-runtime-integration.ts index 691e0ac48c..0c046b2746 100644 --- a/packages/test/src/test-runtime-integration.ts +++ b/packages/test/src/test-runtime-integration.ts @@ -1,8 +1,8 @@ /** * Runtime integration tests. Tests run serially because Runtime is a singleton. * - * These tests deliberately avoid a shared test environment, whose connections would keep the Runtime - * alive: each Worker owns its connection, so the Runtime shuts down once the last Worker stops. + * These tests avoid a shared test environment so they can close every connection and verify that the + * Runtime shuts down automatically once no Workers or connections remain. */ import { randomUUID } from 'crypto'; import asyncRetry from 'async-retry'; @@ -11,8 +11,8 @@ import { Client, Connection, WorkflowClient } from '@temporalio/client'; import type { LogEntry, WorkerOptions } from '@temporalio/worker'; import { DefaultLogger, makeTelemetryFilterString, NativeConnection, Runtime } from '@temporalio/worker'; import { - createWorkerWithOwnConnection, - ownedConnectionConfig, + createWorkerWithConnection, + configuredConnectionOptions, RUN_INTEGRATION_TESTS, test, uniqueTaskQueue, @@ -23,10 +23,10 @@ import { defaultOptions } from './mock-native-worker'; import * as workflows from './workflows'; import { log5Times } from './workflows/runtime'; -const { namespace, connectionOptions } = ownedConnectionConfig(); +const { namespace, connectionOptions } = configuredConnectionOptions(); function createWorker(options: Partial & Pick) { - return createWorkerWithOwnConnection({ ...defaultOptions, ...options }); + return createWorkerWithConnection({ ...defaultOptions, ...options }); } /** @@ -42,46 +42,57 @@ if (RUN_INTEGRATION_TESTS) { test.serial('Runtime tracks registered workers, shuts down and restarts as expected', async (t) => { const taskQueue1 = uniqueTaskQueue(`${t.title} 1`); const taskQueue2 = uniqueTaskQueue(`${t.title} 2`); - const worker1 = await createWorker({ taskQueue: taskQueue1 }); - const worker2 = await createWorker({ taskQueue: taskQueue2 }); + const { worker: worker1, connection: connection1 } = await createWorker({ taskQueue: taskQueue1 }); + const { worker: worker2, connection: connection2 } = await createWorker({ taskQueue: taskQueue2 }); + const runtime = Runtime.instance(); const worker1Drained = worker1.run(); const worker2Drained = worker2.run(); worker1.shutdown(); await worker1Drained; + await connection1.close(); + t.is(Runtime.instance(), runtime); const client = new WorkflowClient({ connection: await connectClient(t), namespace }); await client.execute(workflows.sleeper, { taskQueue: taskQueue2, workflowId: randomUUID(), args: [1] }); worker2.shutdown(); await worker2Drained; + await connection2.close(); - const worker3 = await createWorker({ taskQueue: taskQueue1 }); + const { worker: worker3, connection: connection3 } = await createWorker({ taskQueue: taskQueue1 }); + t.not(Runtime.instance(), runtime); const worker3Drained = worker3.run(); await client.execute('sleeper', { taskQueue: taskQueue1, workflowId: randomUUID(), args: [1] }); worker3.shutdown(); await worker3Drained; - t.pass(); + await connection3.close(); }); test.serial('Runtime.install() remembers installed options after it has been shut down', async (t) => { const messages: string[] = []; const logger = new DefaultLogger('DEBUG', ({ message }) => messages.push(message)); - Runtime.install({ logger }); + const installedRuntime = Runtime.install({ logger }); { const runtime = Runtime.instance(); runtime.logger.info('before shutdown'); t.true(messages.includes('before shutdown')); } - const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); const workerDrained = worker.run(); worker.shutdown(); await workerDrained; + await connection.close(); { - const runtime = Runtime.instance(); - runtime.logger.info('after shutdown'); - t.true(messages.includes('after shutdown')); - await runtime.shutdown(); + const nextConnection = await NativeConnection.connect(connectionOptions); + try { + const runtime = Runtime.instance(); + t.not(runtime, installedRuntime); + runtime.logger.info('after shutdown'); + t.true(messages.includes('after shutdown')); + } finally { + await nextConnection.close(); + } } }); @@ -92,11 +103,16 @@ if (RUN_INTEGRATION_TESTS) { logger, telemetryOptions: { logging: { forward: {}, filter: makeTelemetryFilterString({ core: 'DEBUG' }) } }, }); + const taskQueue = uniqueTaskQueue(t.title); + const client = new Client({ connection: await connectClient(t), namespace }); + const handle = await client.workflow.start('not-existant', { + taskQueue, + workflowId: randomUUID(), + workflowExecutionTimeout: '1m', + }); + t.teardown(() => handle.terminate('test cleanup')); + const { worker, connection } = await createWorker({ taskQueue }); try { - const taskQueue = uniqueTaskQueue(t.title); - const client = new Client({ connection: await connectClient(t), namespace }); - await client.workflow.start('not-existant', { taskQueue, workflowId: randomUUID() }); - const worker = await createWorker({ taskQueue }); await worker.runUntil(() => asyncRetry( () => { @@ -120,7 +136,7 @@ if (RUN_INTEGRATION_TESTS) { t.is(typeof failingWftEntry.meta?.['workflowId'], 'string'); t.is(typeof failingWftEntry.meta?.['sdkComponent'], 'string'); } finally { - await Runtime.instance().shutdown(); + await connection.close(); } }); @@ -155,7 +171,6 @@ if (RUN_INTEGRATION_TESTS) { t.false(logEntries.some((x) => x.message.startsWith('final log'))); } finally { await connection.close(); - await runtime.shutdown(); } t.is(logEntries.filter((x) => x.message.startsWith('workflow log ')).length, 5); diff --git a/packages/test/src/test-worker-lifecycle-integration.ts b/packages/test/src/test-worker-lifecycle-integration.ts index 15b07e7d3a..0121147a33 100644 --- a/packages/test/src/test-worker-lifecycle-integration.ts +++ b/packages/test/src/test-worker-lifecycle-integration.ts @@ -1,71 +1,99 @@ /** * Worker lifecycle integration tests. * - * These tests deliberately avoid a shared test environment: each Worker owns its connection, so the - * Runtime shuts down once the last Worker stops, exactly as it does for a Worker created without one. + * Connections are explicitly closed after their Workers stop. */ import { randomUUID } from 'crypto'; import { setTimeout } from 'timers/promises'; import test from 'ava'; import { Client, Connection } from '@temporalio/client'; import type { WorkerOptions } from '@temporalio/worker'; -import { PromiseCompletionTimeoutError, Runtime, TransportError, UnexpectedError } from '@temporalio/worker'; import { - createWorkerWithOwnConnection, + DefaultLogger, + PromiseCompletionTimeoutError, + Runtime, + TransportError, + UnexpectedError, +} from '@temporalio/worker'; +import { + createWorkerWithConnection, isBun, - ownedConnectionConfig, + configuredConnectionOptions, RUN_INTEGRATION_TESTS, uniqueTaskQueue, } from './helpers'; import { defaultOptions } from './mock-native-worker'; import { fillMemory } from './workflows'; -const { namespace, connectionOptions } = ownedConnectionConfig(); +const { namespace, connectionOptions } = configuredConnectionOptions(); function createWorker(options: Partial & Pick) { - return createWorkerWithOwnConnection({ ...defaultOptions, ...options }); + return createWorkerWithConnection({ ...defaultOptions, ...options }); } if (RUN_INTEGRATION_TESTS) { test.serial('Worker shuts down gracefully', async (t) => { - const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + let flushCalls = 0; + Runtime.install({ + logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { + flush: () => { + flushCalls++; + }, + }), + }); + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); - t.not(Runtime._instance, undefined); const workerRun = worker.run(); t.is(worker.getState(), 'RUNNING'); + const flushesBeforeShutdown = flushCalls; process.emit('SIGINT', 'SIGINT'); await new Promise((resolve) => process.nextTick(resolve)); t.is(worker.getState(), 'DRAINING'); await workerRun; t.is(worker.getState(), 'STOPPED'); + t.true(flushCalls > flushesBeforeShutdown); await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); - t.is(Runtime._instance, undefined); + const flushesBeforeClose = flushCalls; + await connection.close(); + t.true(flushCalls > flushesBeforeClose); }); test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { - const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); - t.not(Runtime._instance, undefined); + let flushCalls = 0; + Runtime.install({ + logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { + flush: () => { + flushCalls++; + }, + }), + }); + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); const p = worker.runUntil( new Promise(() => { // A promise that will never unblock. }) ); t.is(worker.getState(), 'RUNNING'); + const flushesBeforeShutdown = flushCalls; worker.shutdown(); t.is(worker.getState(), 'DRAINING'); await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); t.is(worker.getState(), 'STOPPED'); - t.is(Runtime._instance, undefined); + t.true(flushCalls > flushesBeforeShutdown); + const flushesBeforeClose = flushCalls; + await connection.close(); + t.true(flushCalls > flushesBeforeClose); }); test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { - const worker = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); process.emit('SIGINT', 'SIGINT'); const workerRun = worker.run(); t.is(worker.getState(), 'RUNNING'); await workerRun; t.is(worker.getState(), 'STOPPED'); + await connection.close(); }); test.serial('Worker fails validation against unknown namespace', async (t) => { @@ -86,9 +114,10 @@ if (RUN_INTEGRATION_TESTS) { (isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { t.timeout(30_000); const taskQueue = uniqueTaskQueue(t.title); - const connection = await Connection.connect(connectionOptions); - const client = new Client({ connection, namespace }); - const worker = await createWorker({ taskQueue }); + const clientConnection = await Connection.connect(connectionOptions); + t.teardown(() => clientConnection.close()); + const client = new Client({ connection: clientConnection, namespace }); + const { worker, connection } = await createWorker({ taskQueue }); client.workflow .start(fillMemory, { @@ -118,7 +147,6 @@ if (RUN_INTEGRATION_TESTS) { t.is(worker.getState(), 'FAILED'); } finally { await connection.close(); - if (Runtime._instance) await Runtime._instance.shutdown(); } }); } diff --git a/packages/test/src/test-worker-owned-connection.local.ts b/packages/test/src/test-worker-owned-connection.local.ts new file mode 100644 index 0000000000..e327d41dfd --- /dev/null +++ b/packages/test/src/test-worker-owned-connection.local.ts @@ -0,0 +1,63 @@ +/** + * Implicit connection ownership requires the default local server: Worker.create() cannot configure + * the connection it creates internally. Configured connections are covered by the integration suites. + */ +import { DefaultLogger, PromiseCompletionTimeoutError, Runtime } from '@temporalio/worker'; +import { RUN_INTEGRATION_TESTS, test, uniqueTaskQueue, Worker } from './helpers'; +import { defaultOptions } from './mock-native-worker'; + +if (RUN_INTEGRATION_TESTS) { + test.serial('Worker closes its implicit connection and shuts down the Runtime', async (t) => { + let flushCalls = 0; + Runtime.install({ + logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { + flush: () => { + flushCalls++; + }, + }), + }); + const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); + t.is(worker.getState(), 'INITIALIZED'); + t.not(Runtime._instance, undefined); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + const flushesBeforeShutdown = flushCalls; + process.emit('SIGINT', 'SIGINT'); + await new Promise((resolve) => process.nextTick(resolve)); + t.is(worker.getState(), 'DRAINING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); + t.is(Runtime._instance, undefined); + t.true(flushCalls > flushesBeforeShutdown); + }); + + test.serial( + 'Worker.runUntil closes its implicit connection when the provided promise outlives shutdown', + async (t) => { + let flushCalls = 0; + Runtime.install({ + logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { + flush: () => { + flushCalls++; + }, + }), + }); + const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); + t.not(Runtime._instance, undefined); + const workerRun = worker.runUntil( + new Promise(() => { + // Keep the promise pending so runUntil must time out after Worker shutdown. + }) + ); + t.is(worker.getState(), 'RUNNING'); + const flushesBeforeShutdown = flushCalls; + worker.shutdown(); + t.is(worker.getState(), 'DRAINING'); + await t.throwsAsync(workerRun, { instanceOf: PromiseCompletionTimeoutError }); + t.is(worker.getState(), 'STOPPED'); + t.is(Runtime._instance, undefined); + t.true(flushCalls > flushesBeforeShutdown); + } + ); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 640f84dfb5..4f22c1de1c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -758,6 +758,9 @@ importers: '@temporalio/core-bridge': specifier: workspace:* version: link:../core-bridge + '@temporalio/envconfig': + specifier: workspace:* + version: link:../envconfig '@temporalio/interceptors-opentelemetry': specifier: workspace:* version: link:../../contrib/interceptors-opentelemetry From 0beda946719e2df328e491decc94cd41b790a12d Mon Sep 17 00:00:00 2001 From: Chris Olszewski Date: Mon, 9 Nov 2026 13:08:32 -0500 Subject: [PATCH 5/6] self review --- .../src/test-worker-lifecycle-integration.ts | 40 ++++--------------- .../src/test-worker-owned-connection.local.ts | 33 ++++----------- 2 files changed, 16 insertions(+), 57 deletions(-) diff --git a/packages/test/src/test-worker-lifecycle-integration.ts b/packages/test/src/test-worker-lifecycle-integration.ts index 0121147a33..e555b7da02 100644 --- a/packages/test/src/test-worker-lifecycle-integration.ts +++ b/packages/test/src/test-worker-lifecycle-integration.ts @@ -1,20 +1,16 @@ /** * Worker lifecycle integration tests. * - * Connections are explicitly closed after their Workers stop. + * Run against local servers or Cloud using explicitly supplied connections. Worker shutdown leaves + * these connections open; closing the last connection then shuts down the Runtime. + * Automatic closure of Worker-created connections is covered by test-worker-owned-connection.local.ts. */ import { randomUUID } from 'crypto'; import { setTimeout } from 'timers/promises'; import test from 'ava'; import { Client, Connection } from '@temporalio/client'; import type { WorkerOptions } from '@temporalio/worker'; -import { - DefaultLogger, - PromiseCompletionTimeoutError, - Runtime, - TransportError, - UnexpectedError, -} from '@temporalio/worker'; +import { PromiseCompletionTimeoutError, Runtime, TransportError, UnexpectedError } from '@temporalio/worker'; import { createWorkerWithConnection, isBun, @@ -33,40 +29,22 @@ function createWorker(options: Partial & Pick { - let flushCalls = 0; - Runtime.install({ - logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { - flush: () => { - flushCalls++; - }, - }), - }); const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); const workerRun = worker.run(); t.is(worker.getState(), 'RUNNING'); - const flushesBeforeShutdown = flushCalls; process.emit('SIGINT', 'SIGINT'); await new Promise((resolve) => process.nextTick(resolve)); t.is(worker.getState(), 'DRAINING'); await workerRun; t.is(worker.getState(), 'STOPPED'); - t.true(flushCalls > flushesBeforeShutdown); await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); - const flushesBeforeClose = flushCalls; + t.not(Runtime._instance, undefined, 'The supplied connection keeps the Runtime alive after Worker shutdown'); await connection.close(); - t.true(flushCalls > flushesBeforeClose); + t.is(Runtime._instance, undefined, 'Closing the last supplied connection shuts down the Runtime'); }); test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { - let flushCalls = 0; - Runtime.install({ - logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { - flush: () => { - flushCalls++; - }, - }), - }); const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); const p = worker.runUntil( new Promise(() => { @@ -74,15 +52,13 @@ if (RUN_INTEGRATION_TESTS) { }) ); t.is(worker.getState(), 'RUNNING'); - const flushesBeforeShutdown = flushCalls; worker.shutdown(); t.is(worker.getState(), 'DRAINING'); await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); t.is(worker.getState(), 'STOPPED'); - t.true(flushCalls > flushesBeforeShutdown); - const flushesBeforeClose = flushCalls; + t.not(Runtime._instance, undefined, 'The supplied connection keeps the Runtime alive after Worker shutdown'); await connection.close(); - t.true(flushCalls > flushesBeforeClose); + t.is(Runtime._instance, undefined, 'Closing the last supplied connection shuts down the Runtime'); }); test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { diff --git a/packages/test/src/test-worker-owned-connection.local.ts b/packages/test/src/test-worker-owned-connection.local.ts index e327d41dfd..d522ed7179 100644 --- a/packages/test/src/test-worker-owned-connection.local.ts +++ b/packages/test/src/test-worker-owned-connection.local.ts @@ -1,48 +1,33 @@ /** - * Implicit connection ownership requires the default local server: Worker.create() cannot configure - * the connection it creates internally. Configured connections are covered by the integration suites. + * Verify that Workers close connections they create themselves, shutting down the Runtime without + * an explicit connection.close(). test-worker-lifecycle-integration.ts covers supplied connections, + * which callers must close after Worker shutdown, against both local servers and Cloud. + * These tests require the default local server because Worker.create() accepts connection settings + * only through a supplied connection. */ -import { DefaultLogger, PromiseCompletionTimeoutError, Runtime } from '@temporalio/worker'; +import { PromiseCompletionTimeoutError, Runtime } from '@temporalio/worker'; import { RUN_INTEGRATION_TESTS, test, uniqueTaskQueue, Worker } from './helpers'; import { defaultOptions } from './mock-native-worker'; if (RUN_INTEGRATION_TESTS) { test.serial('Worker closes its implicit connection and shuts down the Runtime', async (t) => { - let flushCalls = 0; - Runtime.install({ - logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { - flush: () => { - flushCalls++; - }, - }), - }); const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); t.is(worker.getState(), 'INITIALIZED'); t.not(Runtime._instance, undefined); const workerRun = worker.run(); t.is(worker.getState(), 'RUNNING'); - const flushesBeforeShutdown = flushCalls; process.emit('SIGINT', 'SIGINT'); await new Promise((resolve) => process.nextTick(resolve)); t.is(worker.getState(), 'DRAINING'); await workerRun; t.is(worker.getState(), 'STOPPED'); await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); - t.is(Runtime._instance, undefined); - t.true(flushCalls > flushesBeforeShutdown); + t.is(Runtime._instance, undefined, 'Worker shutdown closes its implicit connection and shuts down the Runtime'); }); test.serial( 'Worker.runUntil closes its implicit connection when the provided promise outlives shutdown', async (t) => { - let flushCalls = 0; - Runtime.install({ - logger: Object.assign(new DefaultLogger('ERROR', () => undefined), { - flush: () => { - flushCalls++; - }, - }), - }); const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); t.not(Runtime._instance, undefined); const workerRun = worker.runUntil( @@ -51,13 +36,11 @@ if (RUN_INTEGRATION_TESTS) { }) ); t.is(worker.getState(), 'RUNNING'); - const flushesBeforeShutdown = flushCalls; worker.shutdown(); t.is(worker.getState(), 'DRAINING'); await t.throwsAsync(workerRun, { instanceOf: PromiseCompletionTimeoutError }); t.is(worker.getState(), 'STOPPED'); - t.is(Runtime._instance, undefined); - t.true(flushCalls > flushesBeforeShutdown); + t.is(Runtime._instance, undefined, 'runUntil closes the implicit connection and shuts down the Runtime'); } ); } From 61cb88fbbda110b54be36e4256cd1f88ab60ee23 Mon Sep 17 00:00:00 2001 From: Chris Olszewski Date: Mon, 9 Nov 2026 13:17:00 -0500 Subject: [PATCH 6/6] shorten comment --- packages/test/src/test-worker-owned-connection.local.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/test/src/test-worker-owned-connection.local.ts b/packages/test/src/test-worker-owned-connection.local.ts index d522ed7179..e3bc6741f9 100644 --- a/packages/test/src/test-worker-owned-connection.local.ts +++ b/packages/test/src/test-worker-owned-connection.local.ts @@ -1,14 +1,8 @@ -/** - * Verify that Workers close connections they create themselves, shutting down the Runtime without - * an explicit connection.close(). test-worker-lifecycle-integration.ts covers supplied connections, - * which callers must close after Worker shutdown, against both local servers and Cloud. - * These tests require the default local server because Worker.create() accepts connection settings - * only through a supplied connection. - */ import { PromiseCompletionTimeoutError, Runtime } from '@temporalio/worker'; import { RUN_INTEGRATION_TESTS, test, uniqueTaskQueue, Worker } from './helpers'; import { defaultOptions } from './mock-native-worker'; +// These tests are local only as there is no way to provide options to the Worker created connection. if (RUN_INTEGRATION_TESTS) { test.serial('Worker closes its implicit connection and shuts down the Runtime', async (t) => { const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) });