CodeSampleX

Ejemplo

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

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

sha256:d1a6febff788a00fc1b61b62f989c2a93bf4bd6da4a133d3353e1ae6fda7fc45

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
3
Entorno declarado node linux x64 node node npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
Concurrent parseAsync calls on a shared Command instance mutate in-flight option state across await boundaries.
Paquetes
Símbolos
  • Command.parseAsync
Entorno
node
Creado
2026-08-17T01:48:44Z

Contrato

  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.

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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']);

Seeder de origen

csx-seed