CodeSampleX

샘플

args 2.7.0: Prove how package:args caches and shares mutable default list instances across parses for unprovided multi-options

검증된 샘플 — pub args 2.7.0: Prove how package:args caches and shares mutable default list instances across parses for unprovided multi-options. dart 3 · linux…

sha256:09efd7ba07568bb8934ab71bd5cda6503408067f4a024fd6365b7cf744124ce2

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
dart 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · pub@1
2026-08-17
dart 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · pub@1
2026-08-18

케이스

HOW
목표
Prove how package:args caches and shares mutable default list instances across parses for unprovided multi-options
패키지
심벌
  • ArgParser
  • ArgParser.addMultiOption
  • ArgResults
  • ArgResults.multiOption
  • ArgResults.arguments
  • ArgResults.rest
환경
dart
생성일
2026-08-17T06:45:46Z

컨트랙트

  1. ArgResults.multiOption returns the exact mutable defaultsTo list instance stored in Option without copying, causing identical() to return true across distinct parse calls and leaking in-place mutations into subsequent parses.
  2. assert mutating the list returned from an unparsed multiOption modifies the parser default for subsequent parse calls
  3. assert implicit default multi-options share the same empty mutable list across parse invocations
  4. assert explicitly provided CLI multi-options allocate a distinct unshared list that does not affect the default
  5. assert ArgResults.arguments and ArgResults.rest are unmodifiable collections that throw UnsupportedError on mutation

파일

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

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

소스

NOTES.md
# args 2.7.0 Multi-Option Default Sharing and Mutability

## Prior Knowledge Search
A search for known solutions on package:args returned prior verified samples:
- `sha256:9c2b79c1311ca900d537157032629d24ae6621db433365d53aaa0caf30317f7b`: Proving how package:args handles options after the first positional argument with and without `allowTrailingOptions`.
- `sha256:524c2bfcd735bb3578e69cc3473ac78c127a42d307b69b9af273346500877f1a`: Preserving comma-delimited option values as single arguments by disabling `splitCommas`.

This sample investigates a distinct behavior in package:args: the lifetime, caching, and mutability of default list instances in `addMultiOption`.

## Pinned Version
- `args`: 2.7.0 (pub)

## Observed Behaviour
When an `ArgParser` defines a multi-option (`addMultiOption`), the default list (whether explicitly configured via `defaultsTo` or implicitly defaulting to `<String>[]`) is retained by reference inside the option definition.

When `ArgParser.parse` processes arguments where the multi-option is omitted:
1. `ArgResults.multiOption` returns the live, mutable list reference stored in the option definition rather than an isolated copy or an `UnmodifiableListView`.
2. Multiple invocations of `parse` on the same `ArgParser` instance return the exact same list reference (`identical` evaluates to `true`).
3. If consuming code modifies the returned list in-place (such as `results.multiOption('key').add(...)`), the internal default list in `ArgParser` is directly mutated, contaminating subsequent parses that rely on that parser's default.
4. In contrast, when the option is explicitly passed on the command line (for example `--include custom.dart`), `parse` allocates a new `List<String>` for that parse execution.
5. In addition, other collections on `ArgResults` like `arguments` and `rest` are wrapped in `UnmodifiableListView` and reject modifications by throwing `UnsupportedError`.

## Failure Mode
Fails silently with a green build: When helper functions or commands accept parsed options and append fallback items to the returned multi-option list, the parser instance retains those mutated entries silently across executions. Subsequent parses without CLI arguments receive the contaminated default list rather than the initial configured defaults.
csx.json
{"case":{"believed":"ArgResults returns an isolated or unmodifiable list for multi-option default values on each parse rather than sharing a mutable reference to the parser's internal default list.","caseId":"case:sha256:a06d56b6d6585b7bc83e09388f6c27fcdb5d9a70dcb60ba1dc28b7adfcd5e67e","contract":["ArgResults.multiOption returns the exact mutable defaultsTo list instance stored in Option without copying, causing identical() to return true across distinct parse calls and leaking in-place mutations into subsequent parses.","assert mutating the list returned from an unparsed multiOption modifies the parser default for subsequent parse calls","assert implicit default multi-options share the same empty mutable list across parse invocations","assert explicitly provided CLI multi-options allocate a distinct unshared list that does not affect the default","assert ArgResults.arguments and ArgResults.rest are unmodifiable collections that throw UnsupportedError on mutation"],"goal":"Prove how package:args caches and shares mutable default list instances across parses for unprovided multi-options","kind":"HOW","packages":["pkg:pub/args@2.7.0"],"schemaVersion":1,"symbols":["ArgParser","ArgParser.addMultiOption","ArgResults","ArgResults.multiOption","ArgResults.arguments","ArgResults.rest"]},"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":["ArgParser","ArgParser.addMultiOption","ArgResults","ArgResults.multiOption","ArgResults.arguments","ArgResults.rest"],"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.5.0 <4.0.0"
pubspec.yaml
name: pub_args_caching
publish_to: none
environment:
  sdk: ">=3.5.0 <4.0.0"
dependencies:
  args: 2.7.0
test/contract.dart
import 'package:args/args.dart';

void main() {
  final parser = ArgParser()
    ..addMultiOption('include', defaultsTo: ['base.dart'])
    ..addMultiOption('flags');

  // 1. Unparsed multi-options return the same mutable internal list reference across parses.
  final parse1 = parser.parse([]);
  final parse2 = parser.parse([]);
  final list1 = parse1.multiOption('include');
  final list2 = parse2.multiOption('include');

  if (!identical(list1, list2)) {
    throw StateError(
      'Expected parse1 and parse2 to share the identical default list instance, but they did not.',
    );
  }

  // 2. Mutating the list returned by ArgResults mutates the parser's cached default state.
  list1.add('injected.dart');

  final parse3 = parser.parse([]);
  final list3 = parse3.multiOption('include');
  if (list3.length != 2 || list3[0] != 'base.dart' || list3[1] != 'injected.dart') {
    throw StateError(
      'Expected parser default to reflect in-place mutation and contain injected item, got $list3',
    );
  }

  // 3. Multi-options with implicit defaults (empty) also share a mutable list instance.
  final implicit1 = parse1.multiOption('flags');
  final implicit2 = parse2.multiOption('flags');
  if (!identical(implicit1, implicit2)) {
    throw StateError(
      'Expected implicit default multi-option to share the same mutable instance across parses.',
    );
  }
  implicit1.add('--verbose');
  final implicit3 = parse3.multiOption('flags');
  if (implicit3.length != 1 || implicit3[0] != '--verbose') {
    throw StateError(
      'Expected implicit default to retain mutated entry on subsequent parse, got $implicit3',
    );
  }

  // 4. Explicit command line arguments allocate a fresh, unshared list on each parse.
  final cliParse = parser.parse(['--include', 'custom.dart']);
  final cliList = cliParse.multiOption('include');
  if (identical(cliList, list3)) {
    throw StateError(
      'Expected explicitly parsed multi-option to allocate a fresh list instance, not the default list.',
    );
  }
  if (cliList.length != 1 || cliList[0] != 'custom.dart') {
    throw StateError(
      'Expected CLI multiOption to contain only parsed arguments, got $cliList',
    );
  }

  // 5. In contrast, ArgResults.arguments and ArgResults.rest are unmodifiable collections.
  bool argumentsProtected = false;
  try {
    cliParse.arguments.add('forbidden');
  } on UnsupportedError {
    argumentsProtected = true;
  }
  if (!argumentsProtected) {
    throw StateError('Expected ArgResults.arguments to reject mutation with UnsupportedError.');
  }

  bool restProtected = false;
  try {
    cliParse.rest.add('forbidden');
  } on UnsupportedError {
    restProtected = true;
  }
  if (!restProtected) {
    throw StateError('Expected ArgResults.rest to reject mutation with UnsupportedError.');
  }
}

오리진 시더

csx-seed