When a callback executes, does the store visible through getStore() belong to the request whose work is executing? A shared EventEmitter makes that question concrete. If the first listener changes the store, the second listener can read a valid request ID that belongs to somebody else.
The Node.js asynchronous context tracking documentation describes two scopes. AsyncLocalStorage.run() makes its store available to the callback and to asynchronous operations created within it. On return, it restores the caller’s previous context. enterWith() changes the active store for the remainder of the current synchronous execution and propagates it into subsequent asynchronous work.
Ordinary EventEmitter listeners execute synchronously in registration order. Consider a listener registered under request A and invoked outside any request. Then reverse the setup: register the listener outside a request and emit under A. These two cases test an inference from the documented scoping and dispatch rules. A third case, in which the first listener calls enterWith() before the next listener runs, follows Node’s own example.
The request-isolation contract
Suppose the first listener calls enterWith({ requestId: "MUTATED" }). If the second listener reads "MUTATED", an assertion that predicts Node’s behavior can pass even when the application requires that listener to retain A. The Node.js test runner judges the test by whether its function completes or its returned promise fulfills. To judge request isolation, compare the observed store with an independently known request identity.
The nine cases below are EXPECTED / NOT EXECUTED. No store value, timing, hash, exit status, or passing test has been observed. The same distinction matters in validating item processing after asyncio.Queue.join(): a completion signal alone cannot establish which work was performed.
Evidence class | What it establishes |
Documented semantics | Statements directly supported by version-pinned Node.js documentation |
Independent oracle | Expected store identities written before execution |
Observation | Values captured when the fixture is executed |
Operational inference | ACCEPT / REPAIR / RERUN / HOLD after reconciling observation against the oracle |
A zero exit status is necessary when the fixture expects every assertion to pass. ACCEPT also requires the pinned runtime, matching fixture hashes, complete and unique case evidence, expected ordering, and request identities that reconcile with the manifest. Incomplete evidence from an attempted run calls for RERUN. A reproducible, in-scope violation calls for REPAIR. An unexplained contradiction with the documented behavior, or the absence of a run, calls for HOLD.
Source baseline and version boundary
The fixture pins Node.js v24.22.2 LTS, released October 28, 2026. Node 26 LTS was also available when this version was selected. The release-specific documentation defines getStore() as returning the current store, or undefined outside a context initialized by run() or enterWith().
In v24.22.2, enterWith() is marked “Stability: 1 (Experimental).” One handler can call enterWith(store) and a later handler can observe that same store during the same emit(). A single synchronous dispatch is enough to test this behavior. Node recommends preferring run() unless there is a strong reason to use enterWith().
In the expected C05 sequence, request A emits once. The first listener changes the store, then the second listener reads it during the same dispatch.

EXPECTED / NOT EXECUTED. The scope rules and listener order are documented. The request IDs and acceptance policy in this sequence belong to the fixture.
A plain callback created outside a request scope and called inside run() is expected to observe the invocation scope. A custom callback API or thenable that loses context raises a different question. Node’s troubleshooting guidance suggests logging getStore() after suspected calls to locate that boundary. It recommends promisifying callback-based APIs where appropriate, or using AsyncResource to associate a callback with the intended execution context. Only the plain callback is exercised here.
The Node.js async hooks documentation describes an asynchronous resource as an object associated with a callback that can run once or more. It discourages direct use of createHook, AsyncHook, and executionAsyncResource for ordinary context tracking. The observations in this fixture use AsyncLocalStorage and an independently known request ID.
The choice of execution boundary is runtime-specific. A Python asyncio.create_task() context-capture test compares the parent and child request IDs when a task takes its context. With asyncio.to_thread() context capture, constructing the coroutine, scheduling it, and invoking work in the thread are distinct events. In these Node.js emitter cases, the relevant event is invocation of the listener during dispatch.
The built-in test runner is stable. A synchronous throw or a rejected returned promise fails the test. The v24.15.0 test-runner documentation also describes file-level process isolation, where a child’s exit status determines file success. Here the pinned v24.22.2 runner uses one test file, --test-concurrency=1, and a fresh AsyncLocalStorage instance per case. Those choices make the order and state easier to audit.
Fixture assumptions
The commands assume Linux x86-64 and Bash with curl, tar, grep, and sha256sum. Network access is used only to fetch the official Node distribution and checksums. The tests run in one test-file process with synthetic request IDs, zero external npm dependencies, and no production traffic, credentials, databases, queues, services, or HTTP servers.
The cases cover plain callbacks and shared emitters. They make no claims about Worker threads or third-party middleware. Node documents the supplied value as a store and gives no deep-copy guarantee. The shared-reference case tests what happens when the application passes the same mutable object to two request scopes.
Disposable fixture, independent manifest, and controlled cases
Each case creates its own AsyncLocalStorage instance, uses a shared EventEmitter only where needed, and records case-local JSON. Start in a fresh temporary directory and keep the same Bash session for the setup, test, verification, and teardown.
Pin and record the runtime
set -euo pipefail
WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/als-request-isolation.XXXXXX")"
cd "$WORKDIR"
DIST="nodejs.org/dist/v24.22.2"
curl --proto-default https -fsSLO "$DIST/node-v24.22.2-linux-x64.tar.xz"
curl --proto-default https -fsSLO "$DIST/SHASUMS256.txt"
grep ' node-v24.22.2-linux-x64.tar.xz$' SHASUMS256.txt \
| sha256sum -c -
tar -xf node-v24.22.2-linux-x64.tar.xz
NODE="$WORKDIR/node-v24.22.2-linux-x64/bin/node"
"$NODE" --version
"$NODE" -p 'JSON.stringify({
version: process.version,
platform: process.platform,
arch: process.arch,
versions: process.versions
}, null, 2)' > runtime.jsonSave the expected cases in manifest.json
Write the manifest in the temporary working directory before running the tests. expectedObservation is the independently authored prediction of what Node v24.22.2 will expose. contractSatisfied records whether that prediction satisfies the request-isolation policy. In C05 and C07, the predicted behavior violates the policy.
{
"fixture": "als-request-isolation-v1",
"node": "v24.22.2",
"status": "EXPECTED / NOT EXECUTED",
"cases": {
"C01": {
"name": "run establishes isolated request stores across concurrent work",
"expectedObservation": {
"A": ["A", "A"],
"B": ["B", "B"]
},
"contractSatisfied": true
},
"C02": {
"name": "enterWith persists through synchronous execution and created async work",
"expectedObservation": {
"sync": "E",
"async": "E"
},
"contractSatisfied": true
},
"C03": {
"name": "shared emitter listener observes invocation request context",
"expectedObservation": [
{"payload": "A", "store": "A"},
{"payload": "B", "store": "B"}
],
"contractSatisfied": true
},
"C04": {
"name": "negative control: listener registration under A does not by itself bind later invocation",
"expectedObservation": {
"outsideEmitStore": null
},
"contractSatisfied": true
},
"C05": {
"name": "enterWith in first listener contaminates later synchronous listener",
"expectedObservation": {
"secondListener": "MUTATED"
},
"contractSatisfied": false
},
"C06": {
"name": "callback created outside context observes invocation scope",
"expectedObservation": {
"direct": "A",
"setImmediate": "A"
},
"contractSatisfied": true
},
"C07": {
"name": "two run scopes given the same mutable store share the same object reference",
"expectedObservation": {
"before": "base",
"afterOtherScopeMutation": "changed-by-B"
},
"contractSatisfied": false
},
"C08": {
"name": "rejected async operation does not leave request store active in caller",
"expectedObservation": {
"insideBeforeReject": "R",
"outsideAfterReject": null
},
"contractSatisfied": true
},
"C09": {
"name": "repair comparison: listener-local run scope restores original request for later listener",
"expectedObservation": {
"scopedListener": "LOCAL",
"laterListener": "A"
},
"contractSatisfied": true
}
}
}C01 is the positive control for ordinary run() isolation. C04 is the negative control: if a listener registered under A unexpectedly reports A when invoked outside any request, the fixture cannot distinguish registration from invocation. C05 preserves the failing application case. C09 is the controlled comparison using a listener-local run() scope.
Save the nine tests in fixture.test.mjs
Save the complete listing beside manifest.json. Each case writes its observation before comparing it with the manifest. The helper rid() records a missing request ID as JSON null, so the evidence distinguishes an outside-scope read from the literal string IDs used inside the requests.
import test from 'node:test';
import assert from 'node:assert/strict';
import { AsyncLocalStorage } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import {
mkdirSync,
readFileSync,
writeFileSync
} from 'node:fs';
import { setImmediate as immediate } from 'node:timers/promises';
const manifest = JSON.parse(readFileSync('./manifest.json', 'utf8'));
const evidenceDir = './evidence';
mkdirSync(evidenceDir, { recursive: true });
function rid(als) {
return als.getStore()?.requestId ?? null;
}
function persist(caseId, actual) {
const record = {
fixture: manifest.fixture,
caseId,
node: process.version,
observedAt: new Date().toISOString(),
actual
};
writeFileSync(
${evidenceDir}/${caseId}.json,
JSON.stringify(record, null, 2) + '\n',
'utf8'
);
}
function expected(caseId) {
return manifest.cases[caseId].expectedObservation;
}
test('C01 run isolates concurrent request stores', async () => {
const als = new AsyncLocalStorage();
const actual = { A: [], B: [] };
async function request(id) {
return als.run({ requestId: id }, async () => {
actual[id].push(rid(als));
await immediate();
actual[id].push(rid(als));
});
}
await Promise.all([request('A'), request('B')]);
persist('C01', actual);
assert.deepEqual(actual, expected('C01'));
assert.equal(als.getStore(), undefined);
});
test('C02 enterWith persists synchronously and into created async work', async () => {
const als = new AsyncLocalStorage();
als.enterWith({ requestId: 'E' });
const actual = { sync: rid(als), async: null };
await new Promise((resolve) => {
setImmediate(() => {
actual.async = rid(als);
resolve();
});
});
persist('C02', actual);
assert.deepEqual(actual, expected('C02'));
});
test('C03 shared emitter follows invocation request context', async () => {
const als = new AsyncLocalStorage();
const emitter = new EventEmitter();
const actual = [];
emitter.on('work', (payload) => {
actual.push({ payload, store: rid(als) });
});
async function request(id) {
await als.run({ requestId: id }, async () => {
await immediate();
emitter.emit('work', id);
});
}
await request('A');
await request('B');
persist('C03', actual);
assert.deepEqual(actual, expected('C03'));
});
test('C04 negative control: registration is not treated as context binding', () => {
const als = new AsyncLocalStorage();
const emitter = new EventEmitter();
let outsideEmitStore = 'UNSET';
als.run({ requestId: 'A' }, () => {
emitter.on('work', () => {
outsideEmitStore = rid(als);
});
});
emitter.emit('work');
const actual = { outsideEmitStore };
persist('C04', actual);
assert.deepEqual(actual, expected('C04'));
});
test('C05 enterWith contaminates later synchronous listener', () => {
const als = new AsyncLocalStorage();
const emitter = new EventEmitter();
let secondListener = null;
emitter.on('work', () => {
als.enterWith({ requestId: 'MUTATED' });
});
emitter.on('work', () => {
secondListener = rid(als);
});
als.run({ requestId: 'A' }, () => {
emitter.emit('work');
});
const actual = { secondListener };
persist('C05', actual);
assert.deepEqual(actual, expected('C05'));
});
test('C06 callback created outside context reads invocation context', async () => {
const als = new AsyncLocalStorage();
const callback = () => rid(als);
const direct = als.run(
{ requestId: 'A' },
() => callback()
);
let setImmediateValue = null;
await als.run({ requestId: 'A' }, async () => {
await new Promise((resolve) => {
setImmediate(() => {
setImmediateValue = callback();
resolve();
});
});
});
const actual = {
direct,
setImmediate: setImmediateValue
};
persist('C06', actual);
assert.deepEqual(actual, expected('C06'));
});
test('C07 shared mutable store reference is visible across scopes', async () => {
const als = new AsyncLocalStorage();
const shared = {
requestId: 'SHARED',
marker: 'base'
};
let release;
const changed = new Promise((resolve) => {
release = resolve;
});
const actual = {
before: null,
afterOtherScopeMutation: null
};
const a = als.run(shared, async () => {
actual.before = als.getStore().marker;
await changed;
actual.afterOtherScopeMutation = als.getStore().marker;
});
const b = als.run(shared, async () => {
als.getStore().marker = 'changed-by-B';
release();
});
await Promise.all([a, b]);
persist('C07', actual);
assert.deepEqual(actual, expected('C07'));
});
test('C08 rejected async operation leaves caller outside request store', async () => {
const als = new AsyncLocalStorage();
let insideBeforeReject = null;
await assert.rejects(
als.run({ requestId: 'R' }, async () => {
await immediate();
insideBeforeReject = rid(als);
throw new Error('synthetic rejection');
}),
/synthetic rejection/
);
const actual = {
insideBeforeReject,
outsideAfterReject: rid(als)
};
persist('C08', actual);
assert.deepEqual(actual, expected('C08'));
});
test('C09 run scopes listener-local context and restores request A', () => {
const als = new AsyncLocalStorage();
const emitter = new EventEmitter();
let scopedListener = null;
let laterListener = null;
emitter.on('work', () => {
als.run({ requestId: 'LOCAL' }, () => {
scopedListener = rid(als);
});
});
emitter.on('work', () => {
laterListener = rid(als);
});
als.run({ requestId: 'A' }, () => {
emitter.emit('work');
});
const actual = {
scopedListener,
laterListener
};
persist('C09', actual);
assert.deepEqual(actual, expected('C09'));
});Run the fixture and capture the exit status
From the same directory, hash the saved inputs, run the pinned binary, and capture the test process’s exit status. The shell records the Node exit status separately from the output written by tee.
sha256sum manifest.json fixture.test.mjs > fixture.sha256
mkdir -p evidence
set +e
"$NODE" --test --test-reporter=tap --test-concurrency=1 fixture.test.mjs \
2>&1 | tee evidence/test.tap
TEST_STATUS=${PIPESTATUS[0]}
set -e
printf '%s\n' "$TEST_STATUS" > evidence/exit-status.txt
printf 'Evidence files:\n'
find evidence -maxdepth 1 -type f -print | sort
printf 'Fixture hashes:\n'
cat fixture.sha256
printf 'Recorded exit status: %s\n' "$TEST_STATUS"Evidence ledger, reconciliation, recovery, and decision gate
Prepare the ledger before execution. Keep the expectations fixed when recording observations. Each case below is EXPECTED / NOT EXECUTED.
Case | Purpose | Independent expected state | Observed state | Evidence status | Contract implication |
C01 | run() request isolation | A→A/A; B→B/B | NOT EXECUTED | EXPECTED / NOT EXECUTED | Candidate ACCEPT |
C02 | enterWith() persistence | sync E; async E | NOT EXECUTED | EXPECTED / NOT EXECUTED | Boundary evidence |
C03 | Shared emitter invocation | payload A→store A; B→B | NOT EXECUTED | EXPECTED / NOT EXECUTED | Candidate ACCEPT |
C04 | Registration negative control | emit outside→null | NOT EXECUTED | EXPECTED / NOT EXECUTED | Fixture validity |
C05 | enterWith() listener contamination | later listener→MUTATED | NOT EXECUTED | EXPECTED / NOT EXECUTED | REPAIR if observed |
C06 | Outside-created callback | direct A; scheduled A | NOT EXECUTED | EXPECTED / NOT EXECUTED | Callback-boundary evidence |
C07 | Shared mutable store | base→changed-by-B | NOT EXECUTED | EXPECTED / NOT EXECUTED | REPAIR if isolation required |
C08 | Rejected async cleanup | inside R; outside null | NOT EXECUTED | EXPECTED / NOT EXECUTED | Recovery evidence |
C09 | Scoped listener repair | LOCAL then A | NOT EXECUTED | EXPECTED / NOT EXECUTED | Repair comparison |
C05 and C07 can pass their assertions while violating the application contract. In C05, an expected read of "MUTATED" still identifies the wrong request. In C07, request A can see a marker that request B changed because both scopes received the same object.
Use an independent source for each identity comparison. In C03, the payload of emit("work", "A") identifies the source request. In C05 and C09, the enclosing run({ requestId: "A" }) establishes ownership. The manifest fixes the expected observation at each boundary. The same distinction arises when PostgreSQL ON CONFLICT DO NOTHING RETURNING leaves the row ID unresolved. In each case the caller needs an authoritative identity beyond command completion.
A complete run produces C01.json through C09.json exactly once under evidence/, together with test.tap and exit-status.txt. The working directory holds runtime.json and fixture.sha256. A run that aborts after C04 can leave four plausible records and no evidence for the other five cases. Reconciling source rows in pandas GroupBy uses the same check on membership. A plausible result can still omit an expected identity.
Verify case coverage
Save the following verifier as verify-evidence.mjs in the working directory. It checks the set of filenames, the case ID inside each file, and the recorded Node version. A later write can overwrite a file with the same name, so use a fresh directory for every attempt and preserve the resulting evidence bundle.
// verify-evidence.mjs
import assert from 'node:assert/strict';
import { readdirSync, readFileSync } from 'node:fs';
const manifest = JSON.parse(readFileSync('./manifest.json', 'utf8'));
const expectedCases = Object.keys(manifest.cases).sort();
const observedCases = readdirSync('./evidence')
.filter((name) => /^C\d\d\.json$/.test(name))
.map((name) => name.slice(0, -5))
.sort();
assert.deepEqual(
observedCases,
expectedCases,
'missing or duplicate case evidence'
);
for (const caseId of expectedCases) {
const record = JSON.parse(
readFileSync./evidence/${caseId}.json, 'utf8')
);
assert.equal(record.caseId, caseId);
assert.equal(record.node, manifest.node);
}
console.log('evidence-shape-valid');Run the verifier before teardown.
"$NODE" verify-evidence.mjs
The verifier is EXPECTED / NOT EXECUTED. A successful check would establish the expected case files and pinned version. C05 and C07 still require a separate decision about the observed application behavior.
Recovery protocol
Preserve the original manifest, fixture hashes, runtime record, TAP stream, case JSON, and exit status before changing code.
If the runtime or fixture hash differs from the pinned baseline, classify the attempt as RERUN. Repeat it from a fresh directory before interpreting any semantic differences.
If C04 fails its negative control, HOLD the interpretation. Check whether the fixture binds context somewhere the design did not intend.
If C05 shows contamination of the later listener while C03 remains isolated by invocation, apply the C09 repair. Use run() for the listener-local work.
If C07 shows shared-reference mutation, give the requests independently allocated state or use an immutable store. Both scopes can have the correct association and still point to the same mutable object.
Rerun the entire fixture. C01, C03, C04, C06, and C08 guard request identity, callback invocation, negative-control validity, and cleanup.
Roll back the repair if C09 changes unrelated cases or the new evidence cannot be reconciled with the frozen manifest. Record any changed expectation in a new manifest revision.
Scope the repair to the failing case
For C05, both versions run the first listener’s local work under LOCAL. Only the second version restores the surrounding request before the next listener runs.
// Risky for a shared synchronous emitter:
emitter.on('work', () => {
als.enterWith({ requestId: 'LOCAL' });
doLocalWork();
});
// Bounded alternative:
emitter.on('work', () => {
als.run({ requestId: 'LOCAL' }, () => {
doLocalWork();
});
});The callback passed to run() and the asynchronous operations it creates can use the local store. When the callback returns, the shared emitter continues the synchronous dispatch in the surrounding request context. This repair applies to the shared-emitter contract exercised by C05.
For C07, both contexts already use run(). Allocate a separate store for each request so a mutation for B cannot silently redefine A’s identity.
function requestStore(requestId) {
return Object.freeze({ requestId });
}
als.run(requestStore('A'), handleA);
als.run(requestStore('B'), handleB);Freezing each store is an application policy. A request that needs mutable state can receive its own mutable object. The literal A, B, R, LOCAL, and MUTATED values, the payload-to-store match, and the rule used to admit a repair all belong to this fixture.
Apply the decision gate
Evidence condition | Decision | Meaning |
Pinned v24.22.2 and fixture hashes confirmed. Every case is present exactly once. C01, C03, C04, C06, C08, and C09 match the manifest, and no application-contract violation remains in the workflow under review. | ACCEPT | Admit only the tested request-isolation workflow |
A valid fixture deterministically shows C05 contamination or C07 shared-state identity leakage, and the defect is bounded to this code path. | REPAIR | Apply narrow scoping/state-ownership fix, then execute full suite again |
A run was attempted, but its runtime, hashes, logs, case coverage, exit status, or evidence identity is incomplete or inconsistent. | RERUN | Discard that run as admission evidence and repeat from a clean fixture |
No execution evidence exists, the negative control is invalid, valid reruns contradict the pinned documentation, or the scope of a safe repair is unclear. | HOLD | Do not admit the workflow until the uncertainty is resolved |
Current decision: HOLD. All nine cases are EXPECTED / NOT EXECUTED. There are no observations from which to admit the workflow or diagnose a Node defect. A release decision requires the environment, fixture, case coverage, execution order, and observed store values to reconcile with the independently known request identities.
Preserve the evidence before teardown
Copy the manifest, test and verifier files, hashes, runtime record, and evidence directory to the review location before cleanup. Run the following only in the shell where WORKDIR still names the temporary directory created for this attempt.
cd /
rm -rf "$WORKDIR"Backend development with Refonte Learning
For broader backend training, Refonte Learning’s Backend Developer Program lists three months of study at 10–12 hours per week. It specifies a basic understanding of programming and asks applicants to be working toward a bachelor’s degree or higher.
The curriculum covers Node.js and Express, MongoDB and SQL, REST APIs and microservices, authentication and authorization, testing and debugging, Docker and cloud deployment, and a capstone project. The REST API module covers routing, middleware, and database interaction. The program FAQ also names AWS and Azure as examples of cloud platforms used in backend work.
The program describes mentoring, hands-on projects, and potential virtual internships. It lists a Training Certificate and a Certificate of Internship for successful completion, with additional recommendation or appreciation materials conditional on performance. Backend Developer, API Developer, and Database Administrator are listed career paths.
