CodeSampleX

샘플

commander 13.1.0: Concurrent parseAsync calls on a shared Command instance mutate in-flight option state across await boundaries.

검증된 샘플 — npm commander 13.1.0: Concurrent parseAsync calls on a shared Command instance mutate in-flight option state across await boundaries. node 22 …

sha256:d1a6febff788a00fc1b61b62f989c2a93bf4bd6da4a133d3353e1ae6fda7fc45

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-08

케이스

HOW
목표
Concurrent parseAsync calls on a shared Command instance mutate in-flight option state across await boundaries.
패키지
심벌
  • Command.parseAsync
환경
node
생성일
2026-08-17T01:48:44Z

컨트랙트

  1. Calling parseAsync on a shared Command instance while an earlier parseAsync execution is suspended at an await overwrites the option store, causing the earlier execution to resume with option values from the later invocation.
  2. Option values retrieved via cmd.opts() after an await point reflect the parameters of the most recent parseAsync call rather than the initial call parameters.

파일

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Commander Concurrent Execution State Mutation

## Search Results
Calling search_known_solution returned existing samples covering Commander error handling and boolean defaults:
- Sample `94607693bb374f0a65026f93ee8ff32d6560d2668a0b2e16a5e6ebc40f4ddd52`: Distinguishing `exitOverride` error intercept paths for `InvalidArgumentError`.
- Sample `e9734b35dd9bf261570327aa6767cba61b29225dbb1b6eebc59d47cb344f1141`: Paired positive/negative boolean flag default behavior.

This sample addresses a distinct concurrency trap: mutating option state when `Command.parseAsync()` is invoked concurrently on a shared instance.

## Library Behavior
`Command` instances in Commander maintain mutable internal state for options (`_optionValues`) directly on the command object. When `parseAsync()` is called on a shared `Command` instance while a previous `parseAsync()` execution is suspended inside an asynchronous action handler or lifecycle hook:

1. The second `parseAsync()` call resets and overwrites `_optionValues` on the shared instance.
2. When the first execution's action handler resumes after an `await` boundary, calling `cmd.opts()` or `program.opts()` retrieves the option values written by the second invocation.
3. Any downstream actions or postAction hooks on the initial execution observe the mutated option values from the second invocation.

## Failure Mode
A developer or coding model assuming that `parseAsync()` returns an isolated, re-entrant execution promise will write shared `Command` singletons for background task runners or server endpoints.

- **Silent Failure (Green Build)**: In sequential unit tests or single-threaded test suites, each `parseAsync()` call completes before the next begins, concealing the shared state mutation.
- **Runtime Corruption**: In concurrent server environments or async processing pipelines, concurrent invocations silently leak and corrupt option state across in-flight requests without throwing an exception.
csx.json
{"case":{"believed":"Parsing multiple command invocations concurrently with parseAsync on a shared Command instance keeps options isolated within each execution promise.","caseId":"case:sha256:81095fa720797633dfcd243e053872408a81cc971501e04410447f569ac8b182","contract":["Calling parseAsync on a shared Command instance while an earlier parseAsync execution is suspended at an await overwrites the option store, causing the earlier execution to resume with option values from the later invocation.","Option values retrieved via cmd.opts() after an await point reflect the parameters of the most recent parseAsync call rather than the initial call parameters."],"goal":"Concurrent parseAsync calls on a shared Command instance mutate in-flight option state across await boundaries.","kind":"HOW","packages":["pkg:npm/commander@13.1.0"],"schemaVersion":1,"symbols":["Command.parseAsync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@13.1.0"],"schemaVersion":1,"symbols":["Command.parseAsync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-commander-d6",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-commander-d6",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "commander": "^13.1.0"
      }
    },
    "node_modules/commander": {
      "version": "13.1.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
      "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
      "license": "MIT",
      "engines": {
        "node": ">=18"
      }
    }
  }
}
package.json
{
  "name": "npm-commander-d6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "dependencies": {
    "commander": "^13.1.0"
  }
}
src/index.mjs
import { Command } from 'commander';

/**
 * Creates a command configured with an asynchronous action handler and lifecycle hooks.
 *
 * @param {object} [options]
 * @param {Function} [options.actionFn] - Custom action implementation
 * @param {boolean} [options.exitOverride=true] - Whether to override exit behavior
 * @returns {Command}
 */
export function createAsyncServiceCommand(options = {}) {
  const program = new Command();
  if (options.exitOverride !== false) {
    program.exitOverride();
  }

  program
    .name('service')
    .option('-t, --tenant <id>', 'tenant identifier')
    .option('-a, --action-name <name>', 'action name');

  if (options.actionFn) {
    program.action(options.actionFn);
  }

  return program;
}

/**
 * Creates a hierarchical CLI with parent and sibling subcommands.
 *
 * @returns {{ program: Command, deploy: Command, status: Command }}
 */
export function createMultiCommandCLI() {
  const program = new Command('app');
  program.exitOverride();

  const deploy = program
    .command('deploy')
    .option('--env <name>', 'target environment', 'dev')
    .action(() => {});

  const status = program
    .command('status')
    .option('--format <fmt>', 'output format', 'json')
    .action(() => {});

  return { program, deploy, status };
}

/**
 * Creates a CLI command with nested lifecycle hooks to track execution order.
 *
 * @param {string[]} traceLog - Array to push hook execution events into
 * @param {boolean} [throwInAction=false] - Whether the action handler throws an error
 * @returns {Command}
 */
export function createHookedHierarchy(traceLog, throwInAction = false) {
  const program = new Command('root');
  program.exitOverride();

  program
    .hook('preSubcommand', (_thisCmd, subCmd) => {
      traceLog.push(`root:preSubcommand:${subCmd.name()}`);
    })
    .hook('preAction', (_thisCmd, actionCmd) => {
      traceLog.push(`root:preAction:${actionCmd.name()}`);
    })
    .hook('postAction', (_thisCmd, actionCmd) => {
      traceLog.push(`root:postAction:${actionCmd.name()}`);
    });

  program
    .command('child')
    .hook('preAction', (_thisCmd, actionCmd) => {
      traceLog.push(`child:preAction:${actionCmd.name()}`);
    })
    .hook('postAction', (_thisCmd, actionCmd) => {
      traceLog.push(`child:postAction:${actionCmd.name()}`);
    })
    .action(() => {
      traceLog.push('child:action');
      if (throwInAction) {
        throw new Error('action execution failed');
      }
    });

  return program;
}
test/contract.mjs
import { createAsyncServiceCommand } from '../src/index.mjs';
import assert from 'node:assert/strict';

let task1StartedResolve;
const task1Started = new Promise((resolve) => {
  task1StartedResolve = resolve;
});

let task1FinishResolve;
const task1CanFinish = new Promise((resolve) => {
  task1FinishResolve = resolve;
});

const task1Trace = [];
const task2Trace = [];

const program = createAsyncServiceCommand({
  actionFn: async (_opts, cmd) => {
    const tenantAtStart = cmd.opts().tenant;
    if (tenantAtStart === 'alpha') {
      task1Trace.push(tenantAtStart);
      task1StartedResolve();
      await task1CanFinish;
      task1Trace.push(cmd.opts().tenant);
    } else {
      task2Trace.push(tenantAtStart);
      task2Trace.push(cmd.opts().tenant);
    }
  },
});

// 1. Start task 1 with tenant "alpha"
const task1Promise = program.parseAsync(['node', 'service', '-t', 'alpha']);

// 2. Wait until task 1 is suspended inside its async action handler
await task1Started;

// 3. Start task 2 with tenant "beta" while task 1 is in-flight
const task2Promise = program.parseAsync(['node', 'service', '-t', 'beta']);
await task2Promise;

// 4. Resume task 1 after task 2 completed and mutated the Command state
task1FinishResolve();
await task1Promise;

// Contradiction proof:
// Task 1 recorded ['alpha', 'beta'] because cmd.opts().tenant mutated across the await boundary
assert.deepStrictEqual(task1Trace, ['alpha', 'beta']);
assert.deepStrictEqual(task2Trace, ['beta', 'beta']);

오리진 시더

csx-seed