CodeSampleX

Exemplo

args 2.7.0: CommandRunner concurrent execution mutates active command argResults across async await points

Amostra verificada para pub args 2.7.0: CommandRunner concurrent execution mutates active command argResults across async await points. O contrato rodou em…

sha256:25ac71b73fda96d8b3fb6be3afaadce8383fa67d77da5e164dd34c5e6e334d4c

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
2
Ambiente declarado dart linux x64 dart dart pub

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
dart 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · pub@1
2026-08-16
dart 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · pub@1
2026-08-18

Caso

HOW
Objetivo
CommandRunner concurrent execution mutates active command argResults across async await points
Pacotes
Símbolos
  • CommandRunner.run
  • Command.argResults
  • Command.globalResults
Ambiente
dart
Criado
2026-08-17T02:03:23Z

Contrato

  1. Calling CommandRunner.run concurrently while a command is awaiting an asynchronous operation overwrites Command.argResults and Command.globalResults mid-execution with the newly parsed values.
  2. argResults['job'] is 'A' before await, but changes to 'B' after await in the first invocation.
  3. globalResults['env'] is 'staging' before await, but changes to 'production' after await in the first invocation.

Arquivos

  • NOTES.md
  • csx.json
  • pubspec.lock
  • pubspec.yaml
  • test/contract.dart

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Package: args Concurrency and State Reentrancy Behavior

## Known Solutions Found
The initial search for existing samples in package:args returned:
- Goal: args mandatory validation happens on retrieval rather than on parse
- Goal: Preserve comma-delimited option values as single arguments in package:args by disabling splitCommas
- Goal: Build and test a package:args CommandRunner subcommand CLI, telling apart which node reports a UsageException and pinning the option rules that differ from argparse, getopt and clap

## Behavior and Finding
In `package:args`, the `Command` class manages parsed CLI parameters by mutating instance properties (`_argResults` and `_globalResults`). When `CommandRunner.run()` is invoked, it updates these properties on the registered `Command` instance before calling its `run()` method.

If multiple tasks call `CommandRunner.run()` concurrently on the same runner instance while an asynchronous `Command.run()` method is suspended at an `await` point, the second execution overwrites `argResults` and `globalResults` on the `Command` instance. When the first execution resumes after its `await` suspension, calls to `argResults` or `globalResults` retrieve the new arguments from the second execution instead of the original parameters.

## Failure Mode
A model or developer relying on naive execution isolation across asynchronous suspensions will experience a silent green-build logic bug: code compiles cleanly and executes without exceptions, but processes corrupted parameter values post-suspension.
csx.json
{"case":{"believed":"Concurrent invocations of CommandRunner.run maintain isolated argResults and globalResults bindings for each command execution across asynchronous await points.","caseId":"case:sha256:fed4a08e31a5b6da75a404ee3a4609df325cb53d415d1559a9cae1979644af25","contract":["Calling CommandRunner.run concurrently while a command is awaiting an asynchronous operation overwrites Command.argResults and Command.globalResults mid-execution with the newly parsed values.","argResults['job'] is 'A' before await, but changes to 'B' after await in the first invocation.","globalResults['env'] is 'staging' before await, but changes to 'production' after await in the first invocation."],"goal":"CommandRunner concurrent execution mutates active command argResults across async await points","kind":"HOW","packages":["pkg:pub/args@2.7.0"],"schemaVersion":1,"symbols":["CommandRunner.run","Command.argResults","Command.globalResults"]},"contractCommand":["dart","test/contract.dart"],"environment":{"arch":"x64","ecosystem":"pub","executionContext":"dart","language":"dart","os":"linux","packageManager":"pub","runtime":"dart","schemaVersion":1},"license":"MIT-0","packages":["pkg:pub/args@2.7.0"],"schemaVersion":1,"symbols":["CommandRunner.run","Command.argResults","Command.globalResults"],"verifierAdapter":"pub@1"}
pubspec.lock
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
  args:
    dependency: "direct main"
    description:
      name: args
      sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
      url: "https://pub.dev"
    source: hosted
    version: "2.7.0"
sdks:
  dart: ">=3.3.0 <4.0.0"
pubspec.yaml
name: csx_args_test
environment:
  sdk: '>=3.0.0 <4.0.0'

dependencies:
  args: ^2.5.0
test/contract.dart
import 'dart:async';
import 'dart:io';
import 'package:args/command_runner.dart';

class ExecutionLog {
  final String label;
  final String jobBefore;
  final String envBefore;
  String? jobAfter;
  String? envAfter;

  ExecutionLog(this.label, this.jobBefore, this.envBefore);
}

class WorkerCommand extends Command<void> {
  @override
  final String name = 'work';

  @override
  final String description = 'Performs asynchronous work';

  final List<ExecutionLog> logs = [];

  WorkerCommand() {
    argParser.addOption('job');
  }

  @override
  Future<void> run() async {
    final log = ExecutionLog(
      argResults!['job'] as String,
      argResults!['job'] as String,
      globalResults!['env'] as String,
    );
    logs.add(log);

    await Future.delayed(const Duration(milliseconds: 30));

    log.jobAfter = argResults!['job'] as String;
    log.envAfter = globalResults!['env'] as String;
  }
}

Future<void> main() async {
  final runner = CommandRunner<void>('app', 'Test application');
  runner.argParser.addOption('env', defaultsTo: 'prod');

  final worker = WorkerCommand();
  runner.addCommand(worker);

  final firstRun = runner.run(['--env', 'staging', 'work', '--job', 'A']);
  final secondRun = runner.run(['--env', 'production', 'work', '--job', 'B']);

  await Future.wait([firstRun, secondRun]);

  final logA = worker.logs.firstWhere((l) => l.label == 'A');
  final logB = worker.logs.firstWhere((l) => l.label == 'B');

  if (logA.jobBefore != 'A' || logA.envBefore != 'staging') {
    stderr.writeln('Expected logA before await to be job=A, env=staging; got job=${logA.jobBefore}, env=${logA.envBefore}');
    exit(1);
  }

  if (logB.jobBefore != 'B' || logB.envBefore != 'production') {
    stderr.writeln('Expected logB before await to be job=B, env=production; got job=${logB.jobBefore}, env=${logB.envBefore}');
    exit(1);
  }

  if (logA.jobAfter != 'B') {
    stderr.writeln('Expected logA.jobAfter to be mutated to B, got: ${logA.jobAfter}');
    exit(1);
  }

  if (logA.envAfter != 'production') {
    stderr.writeln('Expected logA.envAfter to be mutated to production, got: ${logA.envAfter}');
    exit(1);
  }
}

Seeder de origem

csx-seed