Dashboard › cli › Distillation
39092ecd-b997-4b1c-8123-dff01647eb50["lore_tm_v1_NedNIbRa3CPArbbo7v8T_Hv7vsBd7pV-3jsHQ3KR8xM","lore_tm_v1_BwUVBWo8YJEDH03whDPMWvQdAsHt03h4v6By3T1lYqM"]
/home/byk/.local/share/opencode/worktree/0e8c2f3bbe145a3280d6fb6ed900a5121f382cf0/toolkit-bridge-upgrade/packages/cli/src/lib/delta-upgrade.ts, a 648-line CLI adapter around binpatch that preserves the existing public API while delegating chain extraction, source resolution, caching, patch application, and telemetry.getPrimaryUpgradeSource() returning PRIMARY_UPGRADE_SOURCE or throwing Error("No primary upgrade source is configured").InstrumentHook mapping each HTTP operation to withTracing(name, "http.client", fn).delta-upgrade.ts: patchCacheKey(fromVersion, toVersion) returns patch-chain:${fromVersion}-${toVersion}; load() uses a cache.get span with cache.key, cache.hit, and, on hits, cache.item_size; save() uses a cache.put span keyed from the first stepβs fromVersion through the last stepβs toVersion and records the sum of chain.patches[].size; empty-step saves bypass the span. getPatchCache() wraps makeCache(join(getConfigDir(), "patch-cache")).stableSource() constructing githubReleaseSource() with getGitHubReleasesUrl(source), getPlatformBinaryName(), user agent sentry-cli/${CLI_VERSION}, customFetch, and instrument; nightlySource() constructs ghcrSource() for registry https://ghcr.io, source.ghcrRepo, target tags nightly-${version}, compareVersions, the same user agent, customFetch, and instrument.canAttemptDelta(targetVersion) returning false when CLI_VERSION === "0.0.0-dev", when current and target versions differ in nightly/stable channel, or when isDowngrade(CLI_VERSION, targetVersion) is true; otherwise it returns true.fetchRecentReleases() requesting ${getGitHubReleasesUrl(source)}?per_page=12 via customFetch, with Accept: "application/vnd.github.v3+json" and "User-Agent": \sentry-cli/${CLI_VERSION}`. It returns []` for non-OK responses, non-array JSON, or caught errors, logging debug details for malformed data and failures.downloadStablePatch() using customFetch with the configured user agent and optional signal, returning response bytes as Uint8Array only for an OK response and otherwise returning null; caught failures are debug-logged and return null.extractStableChain() converts any binpatchExtractStableChain() result containing "failure" to null; filterAndSortChainTags() delegates to binpatchFilterAndSortChainTags(..., compareVersions); selected binpatch types and helpers remain re-exported to preserve the existing public API.validateChainStep() retaining richer telemetry classifications than binpatchValidateChainStep(): an incorrect from-version returns { reason: "version-mismatch", expected, actual }; after binpatch validation fails, presence of the exact named layer yields { reason: "size-exceeded", layerSize, budget }, while absence yields { reason: "missing-layer", layerName }. The local three-reason classification is intentionally retained over binpatchβs coarser "malformed" | "over_budget" result.resolveStableChain() directly delegating to stableSource(source).resolveChain(currentVersion, targetVersion, signal).resolveNightlyChain() creating an OciClient for https://ghcr.io with source.ghcrRepo, sentry-cli/${CLI_VERSION}, and customFetch; it uses preloadedTags when supplied or calls listTags(token, PATCH_TAG_PREFIX, signal), filters/sorts tags, and returns null for zero tags or more than MAX_NIGHTLY_CHAIN_DEPTH.resolveNightlyChain() fetching every chain manifest in parallel with Promise.all; a grandfathered silent catch returns null. It then validates ordered steps using the local rich validateChainStep(), sets active-span telemetry_reason to "version-mismatch", "missing-layer", or "size-exceeded" on failure, enforces the remaining budget as fullGzSize * SIZE_THRESHOLD_RATIO - totalSize, derives each destination version by removing PATCH_TAG_PREFIX, and reads the final SHA-256 via getPatchTargetSha256().resolveNightlyChain() returning null with telemetry_reason="version-mismatch" if the chain does not finish at targetVersion or lacks the final expected SHA-256. On success it downloads all digests in parallel through client.downloadBlobBuffer(), wraps them as { data, size }, and returns patches, their reduced totalSize, expectedSha256, and ordered steps.applyPatchChain() running in an "apply-patches" / "upgrade.delta.apply" tracing span, recording patches.count and patches.total_bytes, calling applyPatchChainInMemory(oldBinaryPath, chain.patches.map(patch => patch.data), destPath, onBytes), and throwing SHA-256 mismatch after patching: got ${sha256}, expected ${chain.expectedSha256} when the produced digest differs.makeProgressHandler(): each changed phase gets a fresh progress bar and resets previousWritten; "apply" renders percent-only (format: "pct") because multi-hop totals sum every hopβs newSize and can misleadingly display approximately 930 MB for a 310 MB install, while "download"/"read" and other pre-apply phases retain byte rendering (format: "bytes"). Incremental progress uses event.written - previousWritten, and "done" closes the bar.telemetry() exposes _source.current, captures the resolved source in onResolved, sets delta.source, and logs patch count plus formatted total size; onOfflineMiss captures and reports "offline_miss"; onUnavailable sets telemetry_reason. This retained source lets the catch path attribute apply failures occurring after successful chain resolution.resolveDelta() calling resolveAndApply() with currentVersion: CLI_VERSION, target and file paths, instrumented patch cache, offline mode, phase-aware progress, and telemetry, then returning both { result, source: tel._source.current }. resolveStableDelta() and resolveNightlyDelta() preserve their public call signatures and discard the returned source after selecting the appropriate strategy.attemptDeltaUpgrade() short-circuiting to null when canAttemptDelta() is false, choosing channel "nightly" or "stable" from the target, and tracing under "upgrade.delta" with delta.channel, delta.from_version, and delta.to_version.attemptDeltaUpgrade() telemetry: when a result exists, the span receives delta.patch_bytes and delta.chain_length, and Sentry distributions upgrade.delta.patch_bytes and upgrade.delta.chain_length are emitted with { channel }; an unavailable result gets delta.result="unavailable", and either successful or unavailable resolution sets span status code 1.attemptDeltaUpgrade() catching patch-resolution/application errors, capturing them in Sentry at warning level with tags delta.from_version, delta.to_version, and delta.channel; if resolution had already captured a source, the active error span receives delta.source. It logs Delta upgrade failed (${message}), falling back to full download, sets status code 2, delta.result="error", and delta.error=message, then returns null.prefetch() exits if delta cannot be attempted or the signal is already aborted, resolves a chain from CLI_VERSION, exits if there are no chain.steps or cancellation occurred, and otherwise saves it to the instrumented cache. prefetchNightlyPatches() and prefetchStablePatches() select their respective source strategies./home/byk/.local/share/opencode/worktree/0e8c2f3bbe145a3280d6fb6ed900a5121f382cf0/toolkit-bridge-upgrade/packages/cli/test/lib/delta-upgrade.mocked.test.ts, a 500-line Vitest integration suite that mocks CLI_VERSION as "0.13.0" so orchestration passes the dev-build guard. It is separate from delta-upgrade.test.ts because its vi.mock() reverses dev-mode assumptions; bun test --isolate provides a fresh module graph so mocks do not leak.useTestConfigDir("delta-upgrade-mocked-"), importing production modules after vi.mock("../../src/lib/constants.js", ...), replacing and restoring globalThis.fetch around each test, deriving BINARY_NAME from getPlatformBinaryName(), and generating unique temp paths prefixed delta-iso-.0.13.0 β 0.14.0 hop, a 500-byte patch asset, and a 100,000-byte ${BINARY_NAME}.gz; the downloaded 32-byte fake patch has the TRDIFF10 magic but zero control/diff/new sizes, producing an empty output. Chain discovery and download succeed, but resolveStableDelta("0.14.0", ...) must reject with "SHA-256 mismatch".resolveStableDelta() returning null when every mocked fetch responds HTTP 500.resolveNightlyDelta() null-result tests: (1) token exchange succeeds with "test-token" but the target nightly OCI manifest has a layer titled exactly ${BINARY_NAME} rather than ${BINARY_NAME}.gz; (2) the target has a ${BINARY_NAME}.gz layer sized 30_000_000 but /tags/list returns tags: []. The tags request is mocked in the first case because tag listing runs in parallel with target-manifest fetching.attemptDeltaUpgrade() returning null without network work for a stable-to-nightly request from mocked CLI_VERSION="0.13.0" to "0.0.0-dev.100".attemptDeltaUpgrade("0.14.0", ...) returning null when all stable-chain fetches respond HTTP 500.attemptDeltaUpgrade() catching patch-application failures and returning null: chain resolution succeeds for 0.13.0 β 0.14.0, but the patch download is the invalid byte sequence [0, 1, 2, 3]; the test expects the bspatch error not to escape.../fixtures/patches: small-old.bin is copied to the temporary source, small.trdiff10 is downloaded as an 89-byte patch, and the expected output is small-new.bin with SHA-256 54d0dcd74478bc154b5b24393fdc6129518271baa36f446384d60e84021bb724.attemptDeltaUpgrade("0.14.0", ...) result assertions: sha256 equals 54d0dcd74478bc154b5b24393fdc6129518271baa36f446384d60e84021bb724, patchBytes === 89, and chainLength === 1; the generated destination bytes must exactly equal small-new.bin.