Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## Unreleased

- From core `0.13.0`, the Flutter Apple build error or warning for a
mismatched or earlier-build llama.cpp companion names the companion release
of the core's own minor, such as `^0.13.0`, instead of the first `0.0.x`
release pinning the native runtime.
- With `llamadart_litert_lm_flutter` `0.0.15`, the Flutter macOS build now
only warns to upgrade the companion to `0.0.16`, the release pinning
`v0.18.0-1`, instead of claiming that the app cannot load LiteRT-LM and needs
Expand Down
64 changes: 49 additions & 15 deletions hook/build.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';

import 'package:llamadart/src/hook/apple_companion_constraint.dart';
import 'package:llamadart/src/hook/native_archive_digest.dart';
import 'package:llamadart/src/hook/native_bundle_config.dart';
import 'package:llamadart/src/hook/native_release_pins.dart';
Expand Down Expand Up @@ -685,7 +686,13 @@ _AppleCompanions? _flutterAppleCompanions({
final runtimes = <String>[];
String? liteRtLmMacOsWarning;
if (dependencies.contains(_llamaCppFlutterPackageName)) {
_validateAppleCompanion(_llamaCppCompanion, consumerRoot, output, log);
_validateAppleCompanion(
_llamaCppCompanion,
consumerRoot,
packageRoot,
output,
log,
);
runtimes.add(nativeRuntimeLlamaCpp);
}
if (dependencies.contains(_liteRtLmFlutterPackageName)) {
Expand All @@ -704,6 +711,7 @@ _AppleCompanions? _flutterAppleCompanions({
_validateAppleCompanion(
_stableDiffusionCompanion,
consumerRoot,
packageRoot,
output,
log,
);
Expand All @@ -728,7 +736,8 @@ _AppleCompanions? _flutterAppleCompanions({
/// through `let [tagVariable]` in the maintained manifest template.
/// [compatibleTags] maps earlier tags accepted with a warning to what their
/// frameworks lack. [companionVersion] is the first companion release pinning
/// [nativeTag], when the core records it.
/// [nativeTag], when the core records it; [appleCompanionConstraint] decides
/// whether a build error names it.
typedef _AppleCompanionContract = ({
String label,
String packageName,
Expand Down Expand Up @@ -765,22 +774,24 @@ const _AppleCompanionContract _stableDiffusionCompanion = (
void _validateAppleCompanion(
_AppleCompanionContract contract,
Directory consumerRoot,
Directory packageRoot,
BuildOutputBuilder output,
Logger log,
) {
final companionVersion = contract.companionVersion;
final requiredCompanion = companionVersion == null
? 'Resolve ${contract.packageName} with a Package.swift pin matching '
'${contract.nativeRepository}@${contract.nativeTag} and rerun '
'flutter pub get. '
: 'Depend on `${contract.packageName}: ^$companionVersion`, the first '
'release pinning ${contract.nativeRepository}@'
'${contract.nativeTag}, in pubspec.yaml and rerun flutter pub '
'get; a caret constraint on an earlier 0.0.x release never '
'resolves it. ';
final coreVersion = _corePackageVersion(packageRoot);
final nativePin = '${contract.nativeRepository}@${contract.nativeTag}';
final requiredCompanion =
appleCompanionRequirement(
packageName: contract.packageName,
coreVersion: coreVersion,
nativePin: nativePin,
firstPinningRelease: contract.companionVersion,
) ??
'Resolve ${contract.packageName} with a Package.swift pin matching '
'$nativePin and rerun flutter pub get.';
Never reject(String reason) => throw StateError(
'Incompatible Apple ${contract.label} companion: $reason '
'$requiredCompanion'
'$requiredCompanion '
'Upgrade the core and companion together to a matching released pair; '
'native tag/path overrides do not replace SPM frameworks. '
'No in-process native asset was emitted.',
Expand Down Expand Up @@ -859,12 +870,18 @@ void _validateAppleCompanion(
}
final missing = contract.compatibleTags[pinnedTag];
if (missing != null) {
final constraint = appleCompanionConstraint(
coreVersion,
firstPinningRelease: contract.companionVersion,
);
final next = constraint == null
? 'Upgrade ${contract.packageName} to a release pinning'
: 'Depend on `${contract.packageName}: $constraint` to link';
final upgrade =
'Resolved ${contract.packageName} ${metadata['version']} pins '
'${contract.nativeRepository}@$pinnedTag, an earlier build of the '
'same ${contract.label} runtime as ${contract.nativeTag}, so this '
'build links it. Its frameworks lack $missing. Depend on '
'`${contract.packageName}: ^${contract.companionVersion}` to link '
'build links it. Its frameworks lack $missing. $next '
'${contract.nativeTag}.';
log.warning(upgrade);
stderr.writeln('warning: llamadart: $upgrade');
Expand All @@ -876,6 +893,23 @@ void _validateAppleCompanion(
}
}

/// This core's pubspec `version`, which decides the companion constraint a
/// build error or warning names, or `null` when it cannot be read.
///
/// It is not a build dependency: a cached build emits no error or warning.
String? _corePackageVersion(Directory packageRoot) {
final pubspec = File(path.join(packageRoot.path, 'pubspec.yaml'));
try {
final metadata = loadYaml(pubspec.readAsStringSync());
final version = metadata is Map ? metadata['version'] : null;
return version is String ? version : null;
} on FileSystemException {
return null;
} on FormatException {
return null;
}
}

/// The root of the one [packageName] the consumer's nearest
/// `.dart_tool/package_config.json` resolves; [reject] reports why there is
/// none.
Expand Down
97 changes: 97 additions & 0 deletions lib/src/hook/apple_companion_constraint.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/// The Apple companion dependency `hook/build.dart` tells an app to declare.
library;

/// The first core `MAJOR.MINOR` whose Apple companions share it.
///
/// Companions paired with an earlier core are numbered `0.0.x`.
const appleCompanionLockstepStart = (major: 0, minor: 13);

final RegExp _versionPattern = RegExp(
r'^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$',
);

typedef _Version = ({int major, int minor, int patch, bool prerelease});

_Version? _parse(String? version) {
final match = version == null ? null : _versionPattern.firstMatch(version);
if (match == null) return null;
return (
major: int.parse(match[1]!),
minor: int.parse(match[2]!),
patch: int.parse(match[3]!),
prerelease: match[4] != null,
);
}

bool _isLockstep(_Version core) {
const start = appleCompanionLockstepStart;
if (core.major != start.major) return core.major > start.major;
if (core.minor != start.minor) return core.minor > start.minor;
// A prerelease of the first lockstep version precedes it.
return core.patch > 0 || !core.prerelease;
}

/// Whether core [coreVersion] is at or after `appleCompanionLockstepStart.0`
/// in semver precedence, so its Apple companions share its `MAJOR.MINOR`.
///
/// A prerelease of that first version, such as `0.13.0-dev.1`, is not; a
/// [coreVersion] that is not a version is not either.
bool isAppleCompanionLockstepCore(String coreVersion) {
final core = _parse(coreVersion);
return core != null && _isLockstep(core);
}

/// The pubspec constraint that resolves an Apple companion core
/// [coreVersion] accepts, or `null` when there is none to name.
///
/// [firstPinningRelease] is the first companion release pinning the core's
/// native tag. A lockstep core ([isAppleCompanionLockstepCore]) names it when
/// it shares the core's `MAJOR.MINOR`, because the pin moved within that
/// minor, and otherwise the minor's first release: a caret on a 0.x release,
/// or `'>=FROM <MAJOR.(MINOR+1).0'` once a caret would admit later minors. An
/// earlier core names `^`[firstPinningRelease]. Without a known
/// [firstPinningRelease] nothing names a release that pins the tag, and a
/// missing [coreVersion], or one that is not a version, names nothing.
String? appleCompanionConstraint(
String? coreVersion, {
String? firstPinningRelease,
}) {
final core = _parse(coreVersion);
if (core == null || firstPinningRelease == null) return null;
if (!_isLockstep(core)) return '^$firstPinningRelease';
final first = _parse(firstPinningRelease);
final from =
first != null && first.major == core.major && first.minor == core.minor
? firstPinningRelease
: '${core.major}.${core.minor}.0';
return core.major == 0
? '^$from'
: "'>=$from <${core.major}.${core.minor + 1}.0'";
}

/// The sentence an incompatible Apple companion build error uses to tell the
/// app which [packageName] release to depend on, or `null` when
/// [appleCompanionConstraint] names none.
///
/// [nativePin] is the `repository@tag` the core requires.
String? appleCompanionRequirement({
required String packageName,
required String? coreVersion,
required String nativePin,
String? firstPinningRelease,
}) {
final constraint = appleCompanionConstraint(
coreVersion,
firstPinningRelease: firstPinningRelease,
);
if (constraint == null) return null;
final core = _parse(coreVersion)!;
if (_isLockstep(core)) {
return 'Depend on `$packageName: $constraint`, the core '
'${core.major}.${core.minor}.x companion releases pinning $nativePin, '
'in pubspec.yaml and rerun flutter pub get.';
}
return 'Depend on `$packageName: $constraint`, the first release pinning '
'$nativePin, in pubspec.yaml and rerun flutter pub get; a caret '
'constraint on an earlier 0.0.x release never resolves it.';
}
9 changes: 6 additions & 3 deletions lib/src/hook/native_release_pins.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ const llamaCppTag = 'v0.6.0-3';
/// The first `llamadart_llama_cpp_flutter` release whose `Package.swift` pins
/// [llamaCppTag].
///
/// An incompatible-companion build error names it, because a caret constraint
/// on an earlier `0.0.x` companion can never resolve it. The native pin sync
/// sets it whenever it moves the companion pin.
/// Incompatible-companion build errors name it, because a caret constraint on
/// an earlier companion can never resolve it. A core from
/// `appleCompanionLockstepStart` on names it only when it shares the core's
/// `MAJOR.MINOR`, and its own minor's first release otherwise. The native pin
/// sync sets it to the companion's next release whenever it moves the
/// companion pin.
const llamaCppAppleCompanionVersion = '0.0.23';

/// Earlier `leehack/llamadart-native` tags that a published Apple llama.cpp
Expand Down
28 changes: 28 additions & 0 deletions test/support/hook_core_version.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import 'dart:io';

import 'package:path/path.dart' as path;
import 'package:test/test.dart';

/// The `version` this checkout's core `pubspec.yaml` declares.
String readCheckoutCoreVersion() => RegExp(
r'^version:\s*(\S+)\s*$',
multiLine: true,
).firstMatch(File('pubspec.yaml').readAsStringSync())!.group(1)!;

/// Runs [body] with the build hook's package root at a core declaring
/// [coreVersion], or at this checkout when it is `null`.
///
/// `testCodeBuildHook` takes the package root from [Directory.current], so
/// this overrides it for [body] alone.
Future<void> withHookCoreVersion(
String? coreVersion,
Future<void> Function() body,
) async {
if (coreVersion == null) return body();
final root = await Directory.systemTemp.createTemp('llamadart_core_');
addTearDown(() => root.deleteSync(recursive: true));
File(
path.join(root.path, 'pubspec.yaml'),
).writeAsStringSync('name: llamadart\nversion: $coreVersion\n');
return IOOverrides.runZoned(body, getCurrentDirectory: () => root);
}
Loading
Loading