From df3c34ba25e3d6ce65672cea1fd2361e2e91b2c0 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sun, 8 Nov 2026 08:27:04 -0500 Subject: [PATCH 1/2] Let export-only public entrypoint diffs skip structured-output minima A diff to lib/backend.dart or lib/llamadart.dart that only adds names to show exports now contributes no minimum structured-output impacts, so the evidence may mark them not applicable with a rationale. The evaluator proves it from Git blobs: every non-export line is byte-identical, base exports only gain show names, and each added name resolves to a declaration whose export chain exists at base, sits outside parser, grammar, template and chat-rendering areas, and collides with no other export route. Anything else keeps the full requirement. Fixes #1804. --- doc/high_risk_pre_merge_readiness.md | 27 + .../classify_high_risk_changes_test.dart | 31 ++ .../tooling/high_risk_readiness_test.dart | 521 +++++++++++++++++- tool/testing/classify_high_risk_changes.dart | 24 + tool/testing/high_risk_readiness.dart | 238 +++++++- 5 files changed, 832 insertions(+), 9 deletions(-) diff --git a/doc/high_risk_pre_merge_readiness.md b/doc/high_risk_pre_merge_readiness.md index 19e0a1edc..871822c93 100644 --- a/doc/high_risk_pre_merge_readiness.md +++ b/doc/high_risk_pre_merge_readiness.md @@ -327,6 +327,33 @@ other changed production source, adds any affected chat impact and supplies the corresponding coverage. An internally consistent result still exits 2 for the unconfigured external prerequisites; it never establishes operational readiness. +A second Git-derived refinement covers export-only changes to `lib/backend.dart` +and `lib/llamadart.dart` (`exportOnlyEntrypoints`), such as #1791's +`BackendTextToSpeechModelSupport` SPI export. Such an entrypoint contributes no +minimum impacts, so each impact may be `applicable: false` with a rationale and +production references. Everything else above still applies, including causal +test evidence for the export and the declaring sources' own contributions. + +The entrypoint must be modified in place as a non-executable regular blob at +both revisions, and both revisions must parse. Removing every export +directive's whole lines must leave them byte-identical, so any other changed +line keeps the full requirement: a comment, import, declaration or library doc. +A directive must not share a line with other code or carry annotations. Every +base export stays with the same URI, conditional branches and combinators, +except that a single `show` list may gain names. A new directive must be +unconditional with a single `show`. Removed names, wildcards, `hide` changes and +conditional additions keep the requirement. + +Each added name must resolve through head blobs to its declaration, in every +branch of a conditional export. Every library on that chain must already exist +at base and lie outside structured-output areas. `isStructuredOutputExport` +rejects the classifier's structured paths, including the public entrypoints, +and any path or name containing `chat`, `template`, `jinja`, `render`, +`grammar`, `gbnf`, `schema`, `pars`, `tool`, `structured`, `completion` or +`stream`. No other export route, and no declaration in the entrypoint itself, +may reach an added name. Parts, nonlocal exports, cycles and unknown +declaration shapes on any route the check inspects keep the requirement. + The `families` list retains unique `tested`/`unavailable` entries, relevant tests and a rationale. Missing weights require named unavailable families and primary upstream emissions plus fixtures; unrelated model evidence remains pipeline-only. diff --git a/test/unit/tooling/classify_high_risk_changes_test.dart b/test/unit/tooling/classify_high_risk_changes_test.dart index 6a7a1d1e3..06098a5e6 100644 --- a/test/unit/tooling/classify_high_risk_changes_test.dart +++ b/test/unit/tooling/classify_high_risk_changes_test.dart @@ -72,6 +72,37 @@ void main() { ); }); + test('exports from structured-output areas keep the full requirement', () { + expect( + isStructuredOutputExport( + 'lib/src/backends/backend.dart', + 'BackendTextToSpeechModelSupport', + ), + isFalse, + ); + for (final (path, symbol) in [ + ('lib/src/core/template/chat_format.dart', 'Format'), + ('lib/src/core/grammar/limits.dart', 'Limits'), + ('lib/src/core/models/tools/tool_param.dart', 'Param'), + ('lib/src/core/models/chat/chat_role.dart', 'Role'), + ('lib/src/core/engine/chat_template_renderer.dart', 'Renderer'), + ('lib/src/backends/litert_lm/litert_lm_templates.dart', 'Templates'), + ('lib/src/backends/backend.dart', 'BackendNativeChatGeneration'), + ('lib/src/backends/backend.dart', 'BackendGrammarConstraintsSupport'), + ('lib/src/backends/backend.dart', 'BackendJsonSchemaChatGeneration'), + ('lib/src/backends/backend.dart', 'BackendToolResultMedia'), + ('lib/src/core/engine/engine.dart', 'LlamaEngineCompletionExtension'), + ('lib/src/core/engine/engine.dart', 'ParseResult'), + ('lib/src/core/engine/engine.dart', 'TokenStream'), + ]) { + expect( + isStructuredOutputExport(path, symbol), + isTrue, + reason: '$path $symbol', + ); + } + }); + group('assessHighRiskFiles', () { test('only exact root ffigen config is an artifact consumer', () { expect(assessHighRiskFiles(['ffigen.yaml']).surfaces, { diff --git a/test/unit/tooling/high_risk_readiness_test.dart b/test/unit/tooling/high_risk_readiness_test.dart index 4316b50b8..f8d5ca5a4 100644 --- a/test/unit/tooling/high_risk_readiness_test.dart +++ b/test/unit/tooling/high_risk_readiness_test.dart @@ -1555,8 +1555,8 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; '-j', '1', paths.last, - '--plain-name', - 'Git-bound additive image export impacts', + '--name', + '^Git-bound ', '--exclude-tags', 'local-only', '--reporter', @@ -1578,6 +1578,523 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; timeout: const Timeout(Duration(minutes: 4)), ); + group('Git-bound export-only entrypoint impacts', () { + const entrypoint = 'lib/backend.dart'; + const spi = 'lib/src/backends/backend.dart'; + const entrypointTest = 'test/unit/public_entrypoints_test.dart'; + const addedName = ' BackendTextToSpeechModelSupport,\n'; + const oldEntrypoint = + '/// The service-provider interface for custom llamadart backends.\n' + 'library;\n' + '\n' + "export 'src/backends/backend.dart'\n" + ' show\n' + ' LlamaBackend,\n' + ' BackendTextToSpeech,\n' + ' BackendToolResultMedia;\n' + "export 'src/core/engine/engine.dart' show LlamaEngineBackendHooks;\n"; + final newEntrypoint = oldEntrypoint.replaceFirst( + ' BackendToolResultMedia;', + '$addedName BackendToolResultMedia;', + ); + const oldSpi = + 'abstract class LlamaBackend {}\n' + 'abstract class BackendTextToSpeech {}\n' + 'abstract class BackendToolResultMedia {}\n'; + const newSpi = + '${oldSpi}abstract class BackendTextToSpeechModelSupport {}\n' + 'abstract class BackendChatTemplateSupport {}\n'; + Map> exportFiles({ + String? head, + Map extra = const {}, + }) { + final old = { + for (final entry in extra.entries) + entry.key: (mode: '100644', contents: entry.value), + entrypoint: (mode: '100644', contents: oldEntrypoint), + spi: (mode: '100644', contents: oldSpi), + 'lib/src/core/engine/engine.dart': ( + mode: '100644', + contents: 'class LlamaEngineBackendHooks {}\n', + ), + entrypointTest: ( + mode: '100644', + contents: + "void main() { test('regression case', () { productionCall(); }); }", + ), + }; + return { + baseSha: old, + headSha: { + ...old, + entrypoint: (mode: '100644', contents: head ?? newEntrypoint), + spi: (mode: '100644', contents: newSpi), + }, + }; + } + + const exportChanges = [ + RepositoryChange(path: entrypoint, kind: RepositoryChangeKind.modified), + RepositoryChange(path: spi, kind: RepositoryChangeKind.modified), + ]; + Map exportEvidence(Map extraRefs) { + final evidence = structuredEvidence(); + evidence['surfaces'] = ['structuredOutput', 'backendRuntime']; + evidence['affected_test_paths'] = [entrypointTest]; + final refs = >[ + {'path': entrypoint, 'snippet': 'library;'}, + {'path': spi, 'snippet': 'abstract class LlamaBackend {}'}, + for (final ref in extraRefs.entries) + {'path': ref.key, 'snippet': ref.value}, + ]; + evidence['test_evidence'] = { + entrypointTest: testProof(entrypoint) + ..['production_refs'] = >[ + for (final ref in refs) {...ref}, + ], + }; + final structured = evidence['structured_output_evidence'] as Map; + for (final axis in (structured['coverage'] as Map).keys) { + structured['coverage'][axis] = []; + } + for (final impact in StructuredImpact.values) { + structured['impacts'][impact.name] = { + 'applicable': false, + 'rationale': + 'Independent review: the entrypoint diff only exports the SPI.', + 'production_refs': >[ + for (final ref in refs) {...ref}, + ], + }; + } + structured['families'] = [ + { + 'family': 'speech', + 'status': 'tested', + 'evidence_test_paths': [entrypointTest], + 'rationale': 'No chat or tool-call family is affected.', + }, + ]; + return evidence; + } + + Future evaluateExport({ + Map>? files, + List changes = exportChanges, + Map extraRefs = const {}, + }) { + final state = files ?? exportFiles(); + return HighRiskReadinessEvaluator( + repositoryState: FakeRepositoryState( + changes: changes, + existingPaths: state[headSha]!.keys.toSet(), + files: state, + ), + ).evaluate(evidence: exportEvidence(extraRefs), context: context); + } + + Future expectFullRequirement( + Future evaluation, + ) async { + final result = await evaluation; + expectFailure( + result, + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + expect(result.message, contains('cannot be excluded')); + } + + test('a name added to an existing show export (#1791) may be ' + 'marked not applicable', () async { + final result = await evaluateExport(); + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + expect( + result.failureClassification, + ReadinessFailureClassification.externalPrerequisitesUnavailable, + ); + }); + + final accepted = )>{ + 'a new show export of a non-structured library': ( + "${oldEntrypoint}export 'src/core/speech/voices.dart' show " + 'SpeechVoice;\n', + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + 'a name re-exported through a non-structured library': ( + "${oldEntrypoint}export 'src/core/speech/speech.dart' show " + 'SpeechVoice;\n', + { + 'lib/src/core/speech/speech.dart': + "export 'voices.dart' hide OtherVoice;\n", + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + }, + ), + 'a documented new export': ( + "$oldEntrypoint/// Speech voices.\nexport " + "'src/core/speech/voices.dart' show SpeechVoice;\n", + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + }; + for (final entry in accepted.entries) { + test('${entry.key} may be marked not applicable', () async { + final result = await evaluateExport( + files: exportFiles(head: entry.value.$1, extra: entry.value.$2), + ); + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + }); + } + + final rejected = )>{ + 'an added comment line': ((s) => '$s// Speech\n', {}), + 'a changed library doc comment': ( + (s) => s.replaceFirst('custom llamadart', 'custom'), + {}, + ), + 'an added import': ((s) => "import 'dart:async';\n$s", {}), + 'an added declaration': ((s) => '${s}const version = 1;\n', {}), + 'an export sharing a line with a comment': ( + (s) => s.replaceFirst( + 'LlamaEngineBackendHooks;', + 'LlamaEngineBackendHooks; // hooks', + ), + {}, + ), + 'an annotated export': ( + (s) => s.replaceFirst( + "export 'src/core/engine", + "@Deprecated('x')\nexport 'src/core/engine", + ), + {}, + ), + 'a removed shown name': ( + (s) => s.replaceFirst(' BackendTextToSpeech,\n', ''), + {}, + ), + 'a removed export': ( + (s) => s.replaceFirst( + "export 'src/core/engine/engine.dart' show LlamaEngineBackendHooks;\n", + '', + ), + {}, + ), + 'a structured-output symbol name': ( + (s) => s.replaceFirst( + 'BackendTextToSpeechModelSupport,', + 'BackendChatTemplateSupport,', + ), + {}, + ), + 'a symbol declared in a template library': ( + (s) => "${s}export 'src/core/template/chat_format.dart' show Format;\n", + {'lib/src/core/template/chat_format.dart': 'class Format {}\n'}, + ), + 'a symbol declared in a grammar library': ( + (s) => "${s}export 'src/core/grammar/limits.dart' show Limits;\n", + {'lib/src/core/grammar/limits.dart': 'class Limits {}\n'}, + ), + 'a symbol declared in a chat-rendering library': ( + (s) => "${s}export 'src/core/models/chat/role.dart' show Role;\n", + {'lib/src/core/models/chat/role.dart': 'class Role {}\n'}, + ), + 'a symbol re-exported from a parser library': ( + (s) => "${s}export 'src/core/speech/speech.dart' show Result;\n", + { + 'lib/src/core/speech/speech.dart': + "export '../template/peg_chat_parser.dart';\n", + 'lib/src/core/template/peg_chat_parser.dart': 'class Result {}\n', + }, + ), + 'a symbol re-exported through another public entrypoint': ( + (s) => "${s}export 'llamadart.dart' show SpeechVoice;\n", + {'lib/llamadart.dart': 'class SpeechVoice {}\n'}, + ), + 'a symbol no library declares': ( + (s) => "${s}export 'src/core/speech/voices.dart' show Missing;\n", + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + 'a symbol from a library with parts': ( + (s) => "${s}export 'src/core/speech/voices.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/voices.dart': + "part 'voices_part.dart';\nclass SpeechVoice {}\n", + }, + ), + 'a symbol behind a nonlocal re-export': ( + (s) => "${s}export 'src/core/speech/speech.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/speech.dart': + "export 'package:other/voices.dart';\n", + }, + ), + 'a wildcard new export': ( + (s) => "${s}export 'src/core/speech/voices.dart';\n", + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + 'a hiding new export': ( + (s) => "${s}export 'src/core/speech/voices.dart' hide Other;\n", + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + 'a conditional new export': ( + (s) => + "${s}export 'src/core/speech/voices.dart' if (dart.library.io) " + "'src/core/speech/io_voices.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + 'lib/src/core/speech/io_voices.dart': 'class SpeechVoice {}\n', + }, + ), + 'a repeated export target': ( + (s) => + "${s}export 'src/core/engine/engine.dart' show " + 'LlamaEngineBackendHooks;\n', + {}, + ), + 'invalid syntax': ((s) => '${s}export', {}), + 'an import sharing a line with a new export': ( + (s) => + "${s}import 'dart:async'; export 'src/core/speech/voices.dart' " + 'show SpeechVoice;\n', + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + 'a repeated shown name': ( + (s) => + "${s}export 'src/core/speech/voices.dart' show " + 'SpeechVoice, SpeechVoice;\n', + {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ), + }; + for (final entry in rejected.entries) { + test('${entry.key} keeps the full requirement', () async { + await expectFullRequirement( + evaluateExport( + files: exportFiles( + head: entry.value.$1(newEntrypoint), + extra: entry.value.$2, + ), + ), + ); + }); + } + + final otherRoutes = )>{ + 'another export also reaching the added name': ( + "export 'src/core/speech/voices.dart';\n", + { + 'lib/src/core/speech/voices.dart': + 'class BackendTextToSpeechModelSupport {}\n', + }, + ), + 'another export re-exporting the added name': ( + "export 'src/core/speech/speech.dart' hide Other;\n", + { + 'lib/src/core/speech/speech.dart': "export 'voices.dart';\n", + 'lib/src/core/speech/voices.dart': + 'class BackendTextToSpeechModelSupport {}\n', + }, + ), + 'the entrypoint declaring the added name': ( + 'class BackendTextToSpeechModelSupport {}\n', + {}, + ), + 'an uncertain nonlocal export': ( + "export 'package:other/other.dart';\n", + {}, + ), + 'an uncertain nonlocal re-export': ( + "export 'src/core/speech/speech.dart';\n", + {'lib/src/core/speech/speech.dart': "export 'package:other/a.dart';\n"}, + ), + 'an export cycle': ( + "export 'src/core/speech/a.dart';\n", + { + 'lib/src/core/speech/a.dart': "export 'b.dart';\n", + 'lib/src/core/speech/b.dart': "export 'a.dart';\n", + }, + ), + 'an uncertain export with parts': ( + "export 'src/core/speech/speech.dart';\n", + {'lib/src/core/speech/speech.dart': "part 'speech_part.dart';\n"}, + ), + }; + for (final entry in otherRoutes.entries) { + test('${entry.key} keeps the full requirement', () async { + final files = exportFiles(extra: entry.value.$2); + for (final sha in [baseSha, headSha]) { + files[sha]![entrypoint] = ( + mode: '100644', + contents: files[sha]![entrypoint]!.contents + entry.value.$1, + ); + } + await expectFullRequirement(evaluateExport(files: files)); + }); + } + + test('a name another export hides is not a collision', () async { + final files = exportFiles( + extra: { + 'lib/src/core/speech/voices.dart': + 'class BackendTextToSpeechModelSupport {}\n', + }, + ); + for (final sha in [baseSha, headSha]) { + files[sha]![entrypoint] = ( + mode: '100644', + contents: + "${files[sha]![entrypoint]!.contents}export " + "'src/core/speech/voices.dart' " + 'hide BackendTextToSpeechModelSupport;\n', + ); + } + final result = await evaluateExport(files: files); + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + }); + + test( + 'a name declared in a new library keeps the full requirement', + () async { + final files = exportFiles( + head: + "${oldEntrypoint}export 'src/core/speech/voices.dart' show " + 'SpeechVoice;\n', + ); + files[headSha]!['lib/src/core/speech/voices.dart'] = ( + mode: '100644', + contents: 'class SpeechVoice {}\n', + ); + await expectFullRequirement( + evaluateExport( + files: files, + changes: const [ + ...exportChanges, + RepositoryChange( + path: 'lib/src/core/speech/voices.dart', + kind: RepositoryChangeKind.added, + ), + ], + extraRefs: {'lib/src/core/speech/voices.dart': 'SpeechVoice'}, + ), + ); + }, + ); + + test('a conditional export gaining a name from a structured branch ' + 'keeps the full requirement', () async { + const stub = 'lib/src/backends/speech_stub.dart'; + const io = 'lib/src/core/template/speech_io.dart'; + const directive = + "export 'src/backends/speech_stub.dart'\n" + " if (dart.library.io) 'src/core/template/speech_io.dart'\n"; + final files = exportFiles( + extra: { + stub: 'class Voice {}\nclass Speaker {}\n', + io: 'class Voice {}\nclass Speaker {}\n', + }, + ); + files[baseSha]![entrypoint] = ( + mode: '100644', + contents: '$oldEntrypoint$directive show Voice;\n', + ); + files[headSha]![entrypoint] = ( + mode: '100644', + contents: '$newEntrypoint$directive show Voice, Speaker;\n', + ); + await expectFullRequirement(evaluateExport(files: files)); + for (final sha in [baseSha, headSha]) { + files[sha]![entrypoint] = ( + mode: '100644', + contents: files[sha]![entrypoint]!.contents.replaceFirst( + 'core/template/speech_io', + 'backends/speech_stub_io', + ), + ); + files[sha]!['lib/src/backends/speech_stub_io.dart'] = files[sha]![io]!; + } + final result = await evaluateExport(files: files); + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + }); + + test('a wildcard base export changed to show keeps the full ' + 'requirement', () async { + final base = oldEntrypoint.replaceFirst( + ' show LlamaEngineBackendHooks', + '', + ); + final files = exportFiles(); + files[baseSha]![entrypoint] = (mode: '100644', contents: base); + await expectFullRequirement(evaluateExport(files: files)); + }); + + test('an executable entrypoint keeps the full requirement', () async { + final files = exportFiles(); + files[headSha]![entrypoint] = (mode: '100755', contents: newEntrypoint); + await expectFullRequirement(evaluateExport(files: files)); + }); + + test('a renamed entrypoint keeps the full requirement', () async { + const other = 'lib/backend_spi.dart'; + for (final (from, to) in [(entrypoint, other), (other, entrypoint)]) { + final files = exportFiles(); + files[baseSha]![from] = (mode: '100644', contents: oldEntrypoint); + files[headSha]![to] = (mode: '100644', contents: newEntrypoint); + files[headSha]!.remove(from); + await expectFullRequirement( + evaluateExport( + files: files, + changes: [ + RepositoryChange( + path: to, + kind: RepositoryChangeKind.renamed, + previousPath: from, + ), + exportChanges.last, + ], + extraRefs: {other: 'library;'}, + ), + ); + } + }); + + test('other public entrypoints keep the full requirement', () async { + const bindings = 'lib/llama_cpp_bindings.dart'; + final files = exportFiles(); + for (final sha in [baseSha, headSha]) { + files[sha]![bindings] = files[sha]![entrypoint]!; + } + await expectFullRequirement( + evaluateExport( + files: files, + changes: const [ + ...exportChanges, + RepositoryChange( + path: bindings, + kind: RepositoryChangeKind.modified, + ), + ], + extraRefs: {bindings: 'library;'}, + ), + ); + }); + + test('other changed structured paths keep their own minima', () async { + const parser = 'lib/src/core/template/peg_chat_parser.dart'; + final files = exportFiles(); + files[headSha]![parser] = (mode: '100644', contents: 'class Parser {}'); + final result = await evaluateExport( + files: files, + changes: const [ + ...exportChanges, + RepositoryChange(path: parser, kind: RepositoryChangeKind.added), + ], + extraRefs: {parser: 'class Parser {}'}, + ); + expectFailure( + result, + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + expect(result.message, contains('outputParsingStreaming')); + }); + }); + group('bounded metadata-only release evidence', () { test( 'new release prefix cannot duplicate or invent historical sections', diff --git a/tool/testing/classify_high_risk_changes.dart b/tool/testing/classify_high_risk_changes.dart index 1141477d2..81f499ae3 100644 --- a/tool/testing/classify_high_risk_changes.dart +++ b/tool/testing/classify_high_risk_changes.dart @@ -64,9 +64,33 @@ Set? structuredProductionImpactHints(String path) { return {StructuredImpact.grammarSchema}; } // Handlers, shared utilities, exports, and unknown paths can mix effects. + // Only the readiness evaluator may drop a public entrypoint's contribution, + // after proving its diff export-only (see exportOnlyEntrypoints). return StructuredImpact.values.toSet(); } +/// Public entrypoints whose contribution the readiness evaluator may drop when +/// their diff only adds names to `show` exports. +const Set exportOnlyEntrypoints = { + 'lib/backend.dart', + 'lib/llamadart.dart', +}; + +/// Whether exporting [symbol], declared or re-exported through [path], reaches +/// a parser, grammar, template or chat-rendering area. Such an export keeps +/// the entrypoint's full contribution. +bool isStructuredOutputExport(String path, String symbol) => + _isStructuredOutput(path) || + _structuredExportPattern.hasMatch(path) || + _structuredExportPattern.hasMatch(symbol); + +// Deliberately broad: a false match only keeps the full requirement. +final RegExp _structuredExportPattern = RegExp( + 'chat|template|jinja|render|grammar|gbnf|schema|pars|tool|structured' + '|completion|stream', + caseSensitive: false, +); + /// Platform-independent result of classifying paths read from standard input. class HighRiskCliResult { const HighRiskCliResult({ diff --git a/tool/testing/high_risk_readiness.dart b/tool/testing/high_risk_readiness.dart index 6e09247f7..8e507e672 100644 --- a/tool/testing/high_risk_readiness.dart +++ b/tool/testing/high_risk_readiness.dart @@ -1361,6 +1361,15 @@ class HighRiskReadinessEvaluator { await _isAdditiveImageExport(context, changes, workingDirectory)) { continue; } + if (exportOnlyEntrypoints.contains(path) && + await _isExportOnlyEntrypointChange( + path, + context, + changes, + workingDirectory, + )) { + continue; + } minimumImpacts.addAll(contribution); } if (!hasProductionContribution) { @@ -1394,6 +1403,213 @@ class HighRiskReadinessEvaluator { return null; } + // Adding names to `show` exports cannot change runtime behavior, so the + // entrypoint itself may contribute no minimum impacts. Every other line must + // match the base byte for byte. Each added name must resolve, through head + // blobs, to a declaration whose whole export chain already exists at base + // and stays outside structured-output areas, and no other export route of + // the entrypoint may reach that name. Anything unproven retains the ordinary + // minima; the changed declaring files still contribute their own impacts. + Future _isExportOnlyEntrypointChange( + String entrypoint, + PullRequestContext context, + Map changes, + String? workingDirectory, + ) async { + final change = changes[entrypoint]; + if (change?.kind != RepositoryChangeKind.modified || + change?.previousPath != null) { + return false; + } + Future read(String sha, String path) => + repositoryState.fileAt(sha, path, workingDirectory: workingDirectory); + final base = await read(context.baseSha, entrypoint); + final head = await read(context.headSha, entrypoint); + if (base?.mode != '100644' || head?.mode != '100644') return false; + final baseExports = _exportLines(base!.contents); + final headExports = _exportLines(head!.contents); + if (baseExports == null || + headExports == null || + baseExports.skeleton != headExports.skeleton || + !headExports.byTarget.keys.toSet().containsAll( + baseExports.byTarget.keys, + )) { + return false; + } + final added = >{}; + for (final entry in headExports.byTarget.entries) { + final headDirective = entry.value; + final baseDirective = baseExports.byTarget[entry.key]; + final headShown = _shownNames(headDirective); + if (baseDirective == null) { + if (headShown == null || headDirective.configurations.isNotEmpty) { + return false; + } + added[headDirective] = headShown; + continue; + } + final baseShown = _shownNames(baseDirective); + if (baseShown == null) { + String combinators(ExportDirective directive) => [ + for (final combinator in directive.combinators) combinator.toSource(), + ].join(' '); + if (combinators(headDirective) != combinators(baseDirective)) { + return false; + } + continue; + } + if (headShown == null || !headShown.containsAll(baseShown)) return false; + added[headDirective] = headShown.difference(baseShown); + } + + final units = >{}; + Future headUnit( + String path, + ) => units[path] ??= read(context.headSha, path).then((file) { + final unit = file?.mode == '100644' ? _parseExact(file!.contents) : null; + return unit == null || + _declaredNames(unit) == null || + unit.directives.any( + (directive) => + directive is PartDirective || directive is PartOfDirective, + ) + ? null + : unit; + }); + + // Whether [path] exports [name]; `null` when its export graph is + // uncertain or, for an added name, leaves the reviewed bounds. + Future declares( + String path, + String name, { + required bool addedName, + Set chain = const {}, + }) async { + if (chain.contains(path)) return null; + if (addedName && + (isStructuredOutputExport(path, name) || + (await read(context.baseSha, path))?.mode != '100644')) { + return null; + } + final unit = await headUnit(path); + if (unit == null) return null; + if (_declaredNames(unit)!.contains(name)) return true; + var found = false; + for (final directive in unit.directives.whereType()) { + if (!_exportAdmits(directive, name)) continue; + for (final uri in _exportUris(directive)) { + final child = _localExportPath(path, uri); + if (child == null) return null; + final result = await declares( + child, + name, + addedName: addedName, + chain: {...chain, path}, + ); + if (result == null) return null; + found = found || result; + } + } + return found; + } + + for (final MapEntry(key: adding, value: names) in added.entries) { + for (final name in names) { + if (headExports.declared.contains(name)) return false; + for (final directive in headExports.byTarget.values) { + if (!_exportAdmits(directive, name)) continue; + for (final uri in _exportUris(directive)) { + final target = _localExportPath(entrypoint, uri); + final isAdding = identical(directive, adding); + if (target == null || + await declares(target, name, addedName: isAdding) != isAdding) { + return false; + } + } + } + } + } + return true; + } + + static CompilationUnit? _parseExact(String source) { + final parsed = parseString(content: source, throwIfDiagnostics: false); + return parsed.errors.isEmpty ? parsed.unit : null; + } + + /// Export directives keyed by URI and conditional branches, [source] with + /// each directive's whole lines removed, and the names [source] declares. + /// `null` when a directive shares a line with other code, carries + /// annotations or repeats a key. + static ({ + String skeleton, + Map byTarget, + Set declared, + })? + _exportLines(String source) { + final unit = _parseExact(source); + final declared = unit == null ? null : _declaredNames(unit); + if (unit == null || declared == null) return null; + final byTarget = {}; + final skeleton = StringBuffer(); + var kept = 0; + for (final directive in unit.directives.whereType()) { + final start = source.lastIndexOf('\n', directive.offset - 1) + 1; + final newline = source.indexOf('\n', directive.end); + final end = newline < 0 ? source.length : newline + 1; + final key = [ + directive.uri.stringValue, + for (final branch in directive.configurations) branch.toSource(), + ].join('\n'); + if (start < kept || + directive.metadata.isNotEmpty || + directive.uri.stringValue == null || + source.substring(start, directive.offset).trim().isNotEmpty || + source.substring(directive.end, end).trim().isNotEmpty || + byTarget.containsKey(key)) { + return null; + } + byTarget[key] = directive; + skeleton.write(source.substring(kept, start)); + kept = end; + } + skeleton.write(source.substring(kept)); + return ( + skeleton: skeleton.toString(), + byTarget: byTarget, + declared: declared, + ); + } + + /// The names of [directive]'s single `show` combinator, or `null` for any + /// other combinator shape or a repeated name. + static Set? _shownNames(ExportDirective directive) { + if (directive.combinators.length != 1) return null; + final combinator = directive.combinators.single; + if (combinator is! ShowCombinator) return null; + final names = {for (final name in combinator.shownNames) name.name}; + return names.length == combinator.shownNames.length ? names : null; + } + + static bool _exportAdmits(ExportDirective directive, String name) { + for (final combinator in directive.combinators) { + if (combinator is ShowCombinator && + !combinator.shownNames.any((shown) => shown.name == name)) { + return false; + } + if (combinator is HideCombinator && + combinator.hiddenNames.any((hidden) => hidden.name == name)) { + return false; + } + } + return true; + } + + static List _exportUris(ExportDirective directive) => [ + directive.uri.stringValue, + for (final branch in directive.configurations) branch.uri.stringValue, + ]; + // This recognizes one reviewed export shape, not arbitrary "image paths". // It proves additive namespace/loading properties; the independent review // still owns the behavioral impact decisions and transitive callsite review. @@ -1611,6 +1827,16 @@ class HighRiskReadinessEvaluator { } return false; } + // Existing head image code may reference the new types inside methods. + final declared = _declaredNames(unit); + return declared == null || declared.any(names.contains); + } + + /// Top-level names [unit] declares, or `null` when a declaration node or + /// name shape is unknown. Inspects actual namespace declarations, never a + /// guessed header boundary: record and function return types can contain + /// braces before the name. + static Set? _declaredNames(CompilationUnit unit) { Token? nameAfter(Token keyword, {bool optionalConst = false}) { var token = keyword.next; if (optionalConst && token != null && token.lexeme == 'const') { @@ -1619,9 +1845,7 @@ class HighRiskReadinessEvaluator { return token?.type == TokenType.IDENTIFIER ? token : null; } - // Existing head image code may reference the new types inside methods. - // Inspect actual namespace declarations, never a guessed header boundary: - // record and function return types can contain braces before the name. + final names = {}; for (final declaration in unit.declarations) { final declared = switch (declaration) { // Keyword-anchored name tokens span analyzer 8 through 14. The newer @@ -1648,12 +1872,12 @@ class HighRiskReadinessEvaluator { declared.any( (token) => token == null || token.isSynthetic || token.lexeme.isEmpty, - ) || - declared.any((token) => names.contains(token?.lexeme))) { - return true; + )) { + return null; } + names.addAll(declared.map((token) => token!.lexeme)); } - return false; + return names; } Future<(ReadinessFailureClassification, String)?> _validateEvidencePath( From a023089b86b5e1acb3cb80564bd0bb2cdb073ea1 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sun, 8 Nov 2026 09:11:38 -0500 Subject: [PATCH 2/2] Admit only inert class, enum and mixin exports through the export-only route The independent audit of #1806 showed the exception checked only the added name and its export chain, never what the declaration names: a typedef, subclass or variable aliasing PegChatParser, a named extension, or a top-level jsonEncode shadowing dart:convert all passed. An added name now must be the single class, enum or mixin of that name, shadow no dart:core, dart:async or dart:convert name, and the declaring library may add no structured or other-package import. Every identifier in the declaration is resolved through the library's declarations and imports, transitively, and reaching a structured-output library or an import that cannot be followed keeps the full requirement. --- doc/high_risk_pre_merge_readiness.md | 15 + .../classify_high_risk_changes_test.dart | 5 + .../tooling/high_risk_readiness_test.dart | 342 ++++++++++++++++++ tool/testing/high_risk_readiness.dart | 284 ++++++++++++--- 4 files changed, 595 insertions(+), 51 deletions(-) diff --git a/doc/high_risk_pre_merge_readiness.md b/doc/high_risk_pre_merge_readiness.md index 871822c93..b37140ee3 100644 --- a/doc/high_risk_pre_merge_readiness.md +++ b/doc/high_risk_pre_merge_readiness.md @@ -354,6 +354,21 @@ and any path or name containing `chat`, `template`, `jinja`, `render`, may reach an added name. Parts, nonlocal exports, cycles and unknown declaration shapes on any route the check inspects keep the requirement. +The declaration itself must be the only top-level declaration of that name and +a class, enum or mixin; typedefs, class aliases, functions, getters, variables +and extensions can rebind or extend existing names and keep the requirement, as +does any name that `dart:core`, `dart:async` or `dart:convert` (read from the +running SDK) declares. The declaring library may add no import of a structured +path or another package. Every identifier token in the declaration, from its +annotations to its member bodies, is looked up among the library's own +declarations and every import that admits it, and each declaration found is +checked the same way, transitively. Reaching a structured-output library, or an +import the evaluator cannot follow (another package or an uncertain export +graph), keeps the requirement. Matching tokens by name over-approximates +references, so a member or parameter name equal to a structured export also +keeps it; an existing structured import that provides none of the tokens, such +as `tool_definition.dart` beside #1791's export, does not. + The `families` list retains unique `tested`/`unavailable` entries, relevant tests and a rationale. Missing weights require named unavailable families and primary upstream emissions plus fixtures; unrelated model evidence remains pipeline-only. diff --git a/test/unit/tooling/classify_high_risk_changes_test.dart b/test/unit/tooling/classify_high_risk_changes_test.dart index 06098a5e6..5a57c89e2 100644 --- a/test/unit/tooling/classify_high_risk_changes_test.dart +++ b/test/unit/tooling/classify_high_risk_changes_test.dart @@ -94,6 +94,11 @@ void main() { ('lib/src/core/engine/engine.dart', 'LlamaEngineCompletionExtension'), ('lib/src/core/engine/engine.dart', 'ParseResult'), ('lib/src/core/engine/engine.dart', 'TokenStream'), + ('lib/src/backends/backend.dart', 'JinjaEnvironment'), + ('lib/src/backends/backend.dart', 'RenderOptions'), + ('lib/src/backends/backend.dart', 'GbnfRule'), + ('lib/src/backends/backend.dart', 'SchemaNode'), + ('lib/src/backends/backend.dart', 'StructuredReply'), ]) { expect( isStructuredOutputExport(path, symbol), diff --git a/test/unit/tooling/high_risk_readiness_test.dart b/test/unit/tooling/high_risk_readiness_test.dart index f8d5ca5a4..e29ddcec0 100644 --- a/test/unit/tooling/high_risk_readiness_test.dart +++ b/test/unit/tooling/high_risk_readiness_test.dart @@ -1808,6 +1808,16 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; (s) => "${s}export 'llamadart.dart' show SpeechVoice;\n", {'lib/llamadart.dart': 'class SpeechVoice {}\n'}, ), + 'a symbol re-exported through a structured intermediate library': ( + (s) => "${s}export 'src/core/speech/speech.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/speech.dart': + "export '../template/voices.dart';\n", + 'lib/src/core/template/voices.dart': + "export '../speech/voices.dart';\n", + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + }, + ), 'a symbol no library declares': ( (s) => "${s}export 'src/core/speech/voices.dart' show Missing;\n", {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, @@ -1850,6 +1860,32 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; {}, ), 'invalid syntax': ((s) => '${s}export', {}), + 'two exports on one line': ( + (s) => + "${s}export 'src/core/speech/voices.dart' show SpeechVoice; " + "export 'src/core/speech/speakers.dart' show Speaker;\n", + { + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + 'lib/src/core/speech/speakers.dart': 'class Speaker {}\n', + }, + ), + 'a symbol from a part-of library': ( + (s) => "${s}export 'src/core/speech/voices.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/voices.dart': + "part of 'speech.dart';\nclass SpeechVoice {}\n", + }, + ), + 'a symbol re-exported through a conditional structured branch': ( + (s) => "${s}export 'src/core/speech/speech.dart' show SpeechVoice;\n", + { + 'lib/src/core/speech/speech.dart': + "export 'voices.dart' if (dart.library.io) " + "'../template/io_voices.dart';\n", + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + 'lib/src/core/template/io_voices.dart': 'class SpeechVoice {}\n', + }, + ), 'an import sharing a line with a new export': ( (s) => "${s}import 'dart:async'; export 'src/core/speech/voices.dart' " @@ -1904,6 +1940,16 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; "export 'src/core/speech/speech.dart';\n", {'lib/src/core/speech/speech.dart': "export 'package:other/a.dart';\n"}, ), + 'another export reaching the added name before an unrelated one': ( + "export 'src/core/speech/speech.dart';\n", + { + 'lib/src/core/speech/speech.dart': + "export 'voices.dart';\nexport 'empty.dart';\n", + 'lib/src/core/speech/voices.dart': + 'class BackendTextToSpeechModelSupport {}\n', + 'lib/src/core/speech/empty.dart': 'class Empty {}\n', + }, + ), 'an export cycle': ( "export 'src/core/speech/a.dart';\n", { @@ -2013,6 +2059,302 @@ final segment = '${Object()}ImageEditingRequest${Object()}'; expect(result.decision, ReadinessDecision.unverifiedPrerequisites); }); + for (final (revision, mode) in [(baseSha, '120000'), (headSha, '120000')]) { + test('a declaring library with mode $mode at ' + '${revision == baseSha ? 'base' : 'head'} keeps the full ' + 'requirement', () async { + const voices = 'lib/src/core/speech/voices.dart'; + final files = exportFiles( + head: + "${oldEntrypoint}export 'src/core/speech/voices.dart' show " + 'SpeechVoice;\n', + extra: {voices: 'class SpeechVoice {}\n'}, + ); + files[revision]![voices] = ( + mode: mode, + contents: 'class SpeechVoice {}\n', + ); + await expectFullRequirement(evaluateExport(files: files)); + }); + } + + test( + 'an intermediate library absent at base keeps the full requirement', + () async { + final files = exportFiles( + head: + "${oldEntrypoint}export 'src/core/speech/speech.dart' show " + 'SpeechVoice;\n', + extra: {'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n'}, + ); + files[headSha]!['lib/src/core/speech/speech.dart'] = ( + mode: '100644', + contents: "export 'voices.dart';\n", + ); + files[baseSha]!['lib/src/core/speech/speech.dart'] = ( + mode: '120000', + contents: "export 'voices.dart';\n", + ); + await expectFullRequirement(evaluateExport(files: files)); + }, + ); + + test('a changed conditional branch keeps the full requirement', () async { + const directive = + "export 'src/backends/speech_stub.dart'\n" + " if (dart.library.io) 'src/backends/speech_io.dart'\n" + ' show Voice;\n'; + final files = exportFiles( + extra: { + 'lib/src/backends/speech_stub.dart': 'class Voice {}\n', + 'lib/src/backends/speech_io.dart': 'class Voice {}\n', + 'lib/src/backends/speech_ffi.dart': 'class Voice {}\n', + }, + ); + files[baseSha]![entrypoint] = ( + mode: '100644', + contents: '$oldEntrypoint$directive', + ); + files[headSha]![entrypoint] = ( + mode: '100644', + contents: + newEntrypoint + + directive.replaceFirst('speech_io.dart', 'speech_ffi.dart'), + ); + await expectFullRequirement(evaluateExport(files: files)); + }); + + group('exported declarations', () { + const parser = 'lib/src/core/template/peg_chat_parser.dart'; + const parserImport = "import '../core/template/peg_chat_parser.dart';\n"; + const parserSource = + 'class PegChatParser {}\n' + 'const parserMarker = Object();\n'; + Future evaluateDeclaration( + String name, + String declaration, { + String headImports = '', + String baseImports = '', + Map extra = const {}, + }) { + final files = exportFiles( + head: oldEntrypoint.replaceFirst( + ' BackendToolResultMedia;', + ' $name,\n BackendToolResultMedia;', + ), + extra: {parser: parserSource, ...extra}, + ); + files[baseSha]![spi] = ( + mode: '100644', + contents: '$baseImports$oldSpi', + ); + files[headSha]![spi] = ( + mode: '100644', + contents: '$baseImports$headImports$oldSpi$declaration', + ); + return evaluateExport(files: files); + } + + final bypasses = { + // name, declaration, imports added at head, imports at base + 'an alias of a structured parser': ( + 'BackendReplyReader', + 'typedef BackendReplyReader = PegChatParser;\n', + parserImport, + '', + ), + 'a subclass of a structured parser': ( + 'ReplyReader', + 'class ReplyReader extends PegChatParser {}\n', + parserImport, + '', + ), + 'a variable bound to a structured parser': ( + 'replyReader', + 'final replyReader = PegChatParser.new;\n', + parserImport, + '', + ), + 'a function shadowing dart:convert': ( + 'jsonEncode', + "String jsonEncode(Object? value) => '{}';\n", + '', + '', + ), + 'a named extension': ( + 'Hijack', + "extension Hijack on Object { String toJson() => '{}'; }\n", + '', + '', + ), + 'a class shadowing dart:core': ( + 'Duration', + 'class Duration {}\n', + '', + '', + ), + 'a class shadowing dart:async': ( + 'StreamController', + 'class StreamController {}\n', + '', + '', + ), + 'a class alias': ( + 'BackendMixed', + 'mixin BackendMixin {}\nclass BackendMixed = Object with BackendMixin;\n', + '', + '', + ), + 'a getter': ( + 'backendVersion', + 'int get backendVersion => 1;\n', + '', + '', + ), + 'a member signature naming an existing structured import': ( + 'BackendReplySupport', + 'abstract class BackendReplySupport { PegChatParser reader(); }\n', + '', + parserImport, + ), + 'a member body naming an existing structured import': ( + 'BackendReplySupport', + 'class BackendReplySupport { Object read() => PegChatParser(); }\n', + '', + parserImport, + ), + 'an annotation naming an existing structured import': ( + 'BackendReplySupport', + '@parserMarker\nabstract class BackendReplySupport {}\n', + '', + parserImport, + ), + 'a local alias of a structured parser': ( + 'BackendReplySupport', + 'typedef _Reader = PegChatParser;\n' + 'abstract class BackendReplySupport { _Reader reader(); }\n', + '', + parserImport, + ), + 'a supertype that extends a structured parser elsewhere': ( + 'BackendReplySupport', + 'abstract class BackendReplySupport extends Reader {}\n', + '', + "import '../core/speech/reader.dart';\n", + ), + 'an unrelated class beside an added structured import': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport {}\n', + parserImport, + '', + ), + 'a class beside an added import of another package': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport {}\n', + "import 'package:dinja/dinja.dart';\n", + '', + ), + 'a class beside an added filtered import of another package': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport {}\n', + "import 'package:dinja/dinja.dart' show Template;\n", + '', + ), + 'a reference a structured conditional import branch provides': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport { Reader reader(); }\n', + '', + "import '../core/speech/voices.dart'\n" + " if (dart.library.io) '../core/speech/reader.dart';\n", + ), + 'a name declared twice': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport {}\n' + 'abstract class BackendVoiceSupport {}\n', + '', + '', + ), + 'a reference an uncertain import may provide': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport { Voice voice(); }\n', + '', + "import 'package:other/voices.dart';\n", + ), + }; + for (final entry in bypasses.entries) { + test('${entry.key} keeps the full requirement', () async { + final (name, declaration, headImports, baseImports) = entry.value; + await expectFullRequirement( + evaluateDeclaration( + name, + declaration, + headImports: headImports, + baseImports: baseImports, + extra: { + 'lib/src/core/speech/reader.dart': + "import '../template/peg_chat_parser.dart';\n" + 'abstract class Reader extends PegChatParser {}\n', + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + }, + ), + ); + }); + } + + test('an unreadable SDK keeps the full requirement', () async { + final files = exportFiles(); + final result = await HighRiskReadinessEvaluator( + repositoryState: FakeRepositoryState( + changes: exportChanges, + existingPaths: files[headSha]!.keys.toSet(), + files: files, + ), + dartSdkPath: '${Directory.systemTemp.path}/missing-dart-sdk', + ).evaluate(evidence: exportEvidence(const {}), context: context); + expectFailure( + result, + ReadinessFailureClassification.missingStructuredOutputEvidence, + ); + expect(result.message, contains('cannot be excluded')); + }); + + final allowed = { + 'an enum': ('BackendVoiceKind', 'enum BackendVoiceKind { male }\n', ''), + 'a mixin': ('BackendVoiceMixin', 'mixin BackendVoiceMixin {}\n', ''), + 'an abstract interface class': ( + 'BackendVoiceSupport', + 'abstract interface class BackendVoiceSupport {}\n', + '', + ), + 'a class beside an unrelated existing structured import': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport {\n' + ' Future reason(int handle, List voices);\n' + '}\n', + parserImport, + ), + 'a class naming a non-structured library': ( + 'BackendVoiceSupport', + 'abstract class BackendVoiceSupport { SpeechVoice voice(); }\n', + "import '../core/speech/voices.dart';\n", + ), + }; + for (final entry in allowed.entries) { + test('${entry.key} may be marked not applicable', () async { + final (name, declaration, baseImports) = entry.value; + final result = await evaluateDeclaration( + name, + declaration, + baseImports: baseImports, + extra: { + 'lib/src/core/speech/voices.dart': 'class SpeechVoice {}\n', + }, + ); + expect(result.decision, ReadinessDecision.unverifiedPrerequisites); + }); + } + }); + test('a wildcard base export changed to show keeps the full ' 'requirement', () async { final base = oldEntrypoint.replaceFirst( diff --git a/tool/testing/high_risk_readiness.dart b/tool/testing/high_risk_readiness.dart index 8e507e672..95fd7cc30 100644 --- a/tool/testing/high_risk_readiness.dart +++ b/tool/testing/high_risk_readiness.dart @@ -530,11 +530,16 @@ class HighRiskReadinessEvaluator { const HighRiskReadinessEvaluator({ this.repositoryState = const GitRepositoryStateReader(), this.clock = _defaultClock, + this.dartSdkPath, }); final RepositoryStateReader repositoryState; final DateTime Function() clock; + /// SDK whose `dart:core`, `dart:async` and `dart:convert` names an exported + /// class must not shadow; defaults to the running SDK. + final String? dartSdkPath; + static DateTime _defaultClock() => DateTime.now(); static const _zeroSha = '0000000000000000000000000000000000000000'; static const _rootKeys = { @@ -1403,13 +1408,14 @@ class HighRiskReadinessEvaluator { return null; } - // Adding names to `show` exports cannot change runtime behavior, so the - // entrypoint itself may contribute no minimum impacts. Every other line must - // match the base byte for byte. Each added name must resolve, through head - // blobs, to a declaration whose whole export chain already exists at base - // and stays outside structured-output areas, and no other export route of - // the entrypoint may reach that name. Anything unproven retains the ordinary - // minima; the changed declaring files still contribute their own impacts. + // An entrypoint whose diff only adds names to `show` exports may contribute + // no minimum impacts when each added name is an existing class, enum or + // mixin that shadows no SDK name and names nothing from a structured-output + // library, directly or transitively. Every other line must match the base + // byte for byte, the whole export chain must already exist at base and stay + // outside structured-output areas, and no other export route may reach the + // name. Anything unproven retains the ordinary minima; the changed + // declaring files still contribute their own impacts. Future _isExportOnlyEntrypointChange( String entrypoint, PullRequestContext context, @@ -1477,12 +1483,14 @@ class HighRiskReadinessEvaluator { : unit; }); - // Whether [path] exports [name]; `null` when its export graph is - // uncertain or, for an added name, leaves the reviewed bounds. + // Whether [path] exports [name], collecting the declaring libraries; + // `null` when its export graph is uncertain or, for an added name, leaves + // the reviewed bounds. Future declares( String path, String name, { required bool addedName, + Set? declaringFiles, Set chain = const {}, }) async { if (chain.contains(path)) return null; @@ -1493,17 +1501,21 @@ class HighRiskReadinessEvaluator { } final unit = await headUnit(path); if (unit == null) return null; - if (_declaredNames(unit)!.contains(name)) return true; + if (_declaredNames(unit)!.contains(name)) { + declaringFiles?.add(path); + return true; + } var found = false; for (final directive in unit.directives.whereType()) { - if (!_exportAdmits(directive, name)) continue; - for (final uri in _exportUris(directive)) { + if (!_namespaceAdmits(directive, name)) continue; + for (final uri in _namespaceUris(directive)) { final child = _localExportPath(path, uri); if (child == null) return null; final result = await declares( child, name, addedName: addedName, + declaringFiles: declaringFiles, chain: {...chain, path}, ); if (result == null) return null; @@ -1513,18 +1525,126 @@ class HighRiskReadinessEvaluator { return found; } + // Whether the declarations of [name] in [path], and everything they name + // transitively, stay outside structured-output libraries. Identifier + // tokens over-approximate references: each one is looked up among the + // library's own declarations and every import that admits it, so a member + // or parameter name that matches a structured export also fails closed. + final verdicts = <(String, String), bool>{}; + final visiting = <(String, String)>{}; + Future inert(String path, String name) async { + final key = (path, name); + if (verdicts[key] case final verdict?) return verdict; + // A reference cycle adds nothing; the outer visit decides. + if (!visiting.add(key)) return true; + final verdict = await () async { + if (isStructuredOutputExport(path, '')) return false; + final unit = await headUnit(path); + if (unit == null) return false; + final local = _declaredNames(unit)!; + final declarations = [ + for (final declaration in unit.declarations) + if (_declarationNames(declaration)!.contains(name)) declaration, + ]; + if (declarations.isEmpty) return false; + for (final reference in { + for (final declaration in declarations) + ..._identifierTokens(declaration), + }) { + if (local.contains(reference) && !await inert(path, reference)) { + return false; + } + for (final directive + in unit.directives.whereType()) { + if (!_namespaceAdmits(directive, reference)) continue; + for (final uri in _namespaceUris(directive)) { + if (uri != null && uri.startsWith('dart:')) continue; + final target = _importPath(path, uri); + final declaring = {}; + if (target == null || + await declares( + target, + reference, + addedName: false, + declaringFiles: declaring, + ) == + null) { + return false; + } + for (final file in declaring) { + if (!await inert(file, reference)) return false; + } + } + } + } + return true; + }(); + visiting.remove(key); + return verdicts[key] = verdict; + } + + // An exported class, enum or mixin adds no behavior to existing code + // unless it shadows an SDK name or carries structured-output code with it. + // Other declaration kinds (aliases, functions, variables, extensions) can + // rebind or extend existing names, so they keep the full requirement. + Future exportable(String path, String name) async { + final unit = await headUnit(path); + final sdkNames = _sdkExportNames( + dartSdkPath ?? File(Platform.resolvedExecutable).parent.parent.path, + ); + final declarations = unit?.declarations.where( + (declaration) => _declarationNames(declaration)!.contains(name), + ); + if (sdkNames == null || + sdkNames.contains(name) || + declarations == null || + declarations.length != 1 || + !(declarations.single is ClassDeclaration || + declarations.single is EnumDeclaration || + declarations.single is MixinDeclaration)) { + return false; + } + final base = await read(context.baseSha, path); + final baseUnit = base?.mode == '100644' + ? _parseExact(base!.contents) + : null; + if (baseUnit == null) return false; + Set imports(CompilationUnit source) => { + for (final directive in source.directives.whereType()) + ..._namespaceUris(directive), + }; + for (final uri in imports(unit!).difference(imports(baseUnit))) { + if (uri != null && uri.startsWith('dart:')) continue; + final target = _importPath(path, uri); + if (target == null || isStructuredOutputExport(target, '')) { + return false; + } + } + return inert(path, name); + } + for (final MapEntry(key: adding, value: names) in added.entries) { for (final name in names) { if (headExports.declared.contains(name)) return false; for (final directive in headExports.byTarget.values) { - if (!_exportAdmits(directive, name)) continue; - for (final uri in _exportUris(directive)) { + if (!_namespaceAdmits(directive, name)) continue; + for (final uri in _namespaceUris(directive)) { final target = _localExportPath(entrypoint, uri); final isAdding = identical(directive, adding); + final declaring = {}; if (target == null || - await declares(target, name, addedName: isAdding) != isAdding) { + await declares( + target, + name, + addedName: isAdding, + declaringFiles: declaring, + ) != + isAdding) { return false; } + for (final file in declaring) { + if (!await exportable(file, name)) return false; + } } } } @@ -1532,6 +1652,62 @@ class HighRiskReadinessEvaluator { return true; } + /// Public top-level names of `dart:core`, `dart:async` and `dart:convert` + /// from the [sdk] sources, or `null` when they cannot be read. + static Set? _sdkExportNames(String sdk) => + _sdkExportNamesCache.putIfAbsent(sdk, () { + try { + final names = {}; + for (final library in const ['core', 'async', 'convert']) { + final directory = Directory('$sdk/lib/$library'); + final sources = directory.listSync().whereType().where( + (file) => file.path.endsWith('.dart'), + ); + for (final source in sources) { + final unit = parseString( + content: source.readAsStringSync(), + throwIfDiagnostics: false, + ).unit; + for (final declaration in unit.declarations) { + // Built-in identifiers such as `Function` cannot be redeclared. + final declared = _declarationNames(declaration) ?? const []; + names.addAll(declared.where((name) => !name.startsWith('_'))); + } + } + } + return names.contains('Future') && + names.contains('jsonEncode') && + names.contains('StreamController') + ? names + : null; + } on FileSystemException { + return null; + } + }); + static final _sdkExportNamesCache = ?>{}; + + /// Every identifier token of [declaration], its annotations included. + static Set _identifierTokens(CompilationUnitMember declaration) { + final names = {}; + var token = declaration.metadata.isEmpty + ? declaration.firstTokenAfterCommentAndMetadata + : declaration.metadata.first.beginToken; + while (true) { + if (token.type == TokenType.IDENTIFIER) names.add(token.lexeme); + if (token == declaration.endToken || token.isEof) return names; + token = token.next!; + } + } + + /// The repository path an import [value] in [source] names, or `null` for + /// another package or an unsupported form. + static String? _importPath(String source, String? value) { + const self = 'package:llamadart/'; + return value != null && value.startsWith(self) + ? _localExportPath('lib/llamadart.dart', value.substring(self.length)) + : _localExportPath(source, value); + } + static CompilationUnit? _parseExact(String source) { final parsed = parseString(content: source, throwIfDiagnostics: false); return parsed.errors.isEmpty ? parsed.unit : null; @@ -1561,8 +1737,7 @@ class HighRiskReadinessEvaluator { directive.uri.stringValue, for (final branch in directive.configurations) branch.toSource(), ].join('\n'); - if (start < kept || - directive.metadata.isNotEmpty || + if (directive.metadata.isNotEmpty || directive.uri.stringValue == null || source.substring(start, directive.offset).trim().isNotEmpty || source.substring(directive.end, end).trim().isNotEmpty || @@ -1591,7 +1766,7 @@ class HighRiskReadinessEvaluator { return names.length == combinator.shownNames.length ? names : null; } - static bool _exportAdmits(ExportDirective directive, String name) { + static bool _namespaceAdmits(NamespaceDirective directive, String name) { for (final combinator in directive.combinators) { if (combinator is ShowCombinator && !combinator.shownNames.any((shown) => shown.name == name)) { @@ -1605,7 +1780,7 @@ class HighRiskReadinessEvaluator { return true; } - static List _exportUris(ExportDirective directive) => [ + static List _namespaceUris(NamespaceDirective directive) => [ directive.uri.stringValue, for (final branch in directive.configurations) branch.uri.stringValue, ]; @@ -1837,6 +2012,18 @@ class HighRiskReadinessEvaluator { /// guessed header boundary: record and function return types can contain /// braces before the name. static Set? _declaredNames(CompilationUnit unit) { + final names = {}; + for (final declaration in unit.declarations) { + final declared = _declarationNames(declaration); + if (declared == null) return null; + names.addAll(declared); + } + return names; + } + + /// Names [declaration] declares, or `null` for an unknown node or name + /// shape. + static List? _declarationNames(CompilationUnitMember declaration) { Token? nameAfter(Token keyword, {bool optionalConst = false}) { var token = keyword.next; if (optionalConst && token != null && token.lexeme == 'const') { @@ -1845,39 +2032,34 @@ class HighRiskReadinessEvaluator { return token?.type == TokenType.IDENTIFIER ? token : null; } - final names = {}; - for (final declaration in unit.declarations) { - final declared = switch (declaration) { - // Keyword-anchored name tokens span analyzer 8 through 14. The newer - // namePart API is absent, nullable or gated in allowed older versions. - ClassDeclaration() => [nameAfter(declaration.classKeyword)], - ClassTypeAlias() => [declaration.name], - EnumDeclaration() => [nameAfter(declaration.enumKeyword)], - MixinDeclaration() => [declaration.name], - ExtensionDeclaration() => [ - if (declaration.name != null) declaration.name!, - ], - ExtensionTypeDeclaration() => [ - nameAfter(declaration.typeKeyword, optionalConst: true), - ], - FunctionDeclaration() => [declaration.name], - FunctionTypeAlias() => [declaration.name], - GenericTypeAlias() => [declaration.name], - TopLevelVariableDeclaration() => [ - for (final variable in declaration.variables.variables) variable.name, - ], - _ => null, - }; - if (declared == null || - declared.any( - (token) => - token == null || token.isSynthetic || token.lexeme.isEmpty, - )) { - return null; - } - names.addAll(declared.map((token) => token!.lexeme)); + final declared = switch (declaration) { + // Keyword-anchored name tokens span analyzer 8 through 14. The newer + // namePart API is absent, nullable or gated in allowed older versions. + ClassDeclaration() => [nameAfter(declaration.classKeyword)], + ClassTypeAlias() => [declaration.name], + EnumDeclaration() => [nameAfter(declaration.enumKeyword)], + MixinDeclaration() => [declaration.name], + ExtensionDeclaration() => [ + if (declaration.name != null) declaration.name!, + ], + ExtensionTypeDeclaration() => [ + nameAfter(declaration.typeKeyword, optionalConst: true), + ], + FunctionDeclaration() => [declaration.name], + FunctionTypeAlias() => [declaration.name], + GenericTypeAlias() => [declaration.name], + TopLevelVariableDeclaration() => [ + for (final variable in declaration.variables.variables) variable.name, + ], + _ => null, + }; + if (declared == null || + declared.any( + (token) => token == null || token.isSynthetic || token.lexeme.isEmpty, + )) { + return null; } - return names; + return [for (final token in declared) token!.lexeme]; } Future<(ReadinessFailureClassification, String)?> _validateEvidencePath(