From 0cbd21f53fe322e963487ebe8b5510581ec460fa Mon Sep 17 00:00:00 2001 From: John Trujillo Date: Wed, 16 Sep 2026 12:55:26 -0500 Subject: [PATCH 1/5] ADFA-6053: Publish an embedding capability in the plugin API A backend had no way to tell the IDE it can turn text into vectors. The only embedding entry point was LlmInferenceService.getEmbeddings(String, String), which addresses a backend by id and returns a bare float[]: the caller learns neither which model produced the vector nor how long it is, and pays one round trip per text. Indexing a project is thousands of chunks, so that is thousands of requests on a phone, and a stored vector carries no provenance -- swapping the model behind a backend silently degrades every vector already on disk instead of invalidating it. Add LlmInferenceService.EmbeddingBackend extends LlmBackend, an optional capability interface alongside ToolCallingBackend, HistoryCapableBackend, CancellableBackend and ConfigurableBackend, so a consumer asks for it with instanceof rather than by a flag a backend can set inconsistently with the methods it overrode. It declares embed(List) returning CompletableFuture> index-aligned with the input, getEmbeddingDimensions() and getEmbeddingModelId() -- the model's identity, not the backend's, because two models of equal width are mutually incomparable and a width check alone cannot detect a swap. The interface documentation states the contracts a caller cannot verify at runtime: the batch completes whole or fails whole, never yielding a short list, a list padded with nulls or a placeholder vector; embed must not block the calling thread and must be safe for concurrent calls; every failure is reported by completing the future exceptionally, with a synchronous throw reserved for the caller's own mistake. getEmbeddings(String, String) stays -- the Vector-Search plugin is a live caller and removing it breaks already-built .cgp files. Nothing behavioural ships here. The change is a declaration with no implementation, and the regenerated ABI dump is six added lines with no removals, so a plugin that does not implement the interface keeps loading and running against the refreshed jar. plugin-api/api/plugin-api.api is regenerated by :plugin-api:apiDump and belongs in this commit: binary-compatibility-validator fails apiCheck without it. --- docs/PLUGIN_API_CHANGELOG.md | 30 ++ docs/plugin-api.md | 2 +- plugin-api/api/plugin-api.api | 6 + .../plugins/services/LlmInferenceService.java | 61 +++- .../services/LlmInferenceServiceTest.java | 276 +++++++++++++++++- 5 files changed, 372 insertions(+), 3 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 09f263ea59..0d38c10e61 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,6 +35,36 @@ need a source change, a recompile, or both · `tooling` = API-stability milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]** = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). +### 26.39 — unreleased +- **added — An embedding capability a backend can declare** _(ADFA-6053)_ **[verified]** + A backend that has an embedding model can now say so. The only embedding entry point + before this was `LlmInferenceService.getEmbeddings(String, String)`, which addresses a + backend by id and hands back a bare `float[]`: the caller learns neither which model + produced the vector nor how long it is, and pays one round trip per text. Indexing a + project is thousands of chunks, so that is thousands of requests, and a stored vector + carries no provenance — swapping the model behind a backend silently degrades every + vector already on disk instead of invalidating it. + `LlmInferenceService.EmbeddingBackend extends LlmBackend` is an optional capability + interface, like `ToolCallingBackend` and `HistoryCapableBackend`: implement it and the + consumer finds it with `instanceof`, there is no flag to set. It declares + `embed(List)` returning `CompletableFuture>` index-aligned with + the input, `getEmbeddingDimensions()`, and `getEmbeddingModelId()` — the model's + identity, not the backend's, because two models of equal width are mutually + incomparable and a width check alone cannot detect a swap. + The batch either completes whole or fails whole; it never yields a short list, a list + padded with nulls, or a placeholder vector, so a caller can never store a partially-real + batch. `embed` must not block the calling thread and must be safe for concurrent calls + (indexing and a user's query can be in flight at once); it reports every failure by + completing the future exceptionally and throws synchronously only for a caller's own + mistake — `NullPointerException` for a null argument or element, `IllegalArgumentException` + for an empty list. + Purely additive: a new interface with three new methods, nothing existing changed (the + ABI dump diff is six added lines and no removals), so an already-built `.cgp` keeps + loading and running against the refreshed jar. `getEmbeddings(String, String)` stays — + the Vector-Search plugin is a live caller. Floor `plugin.min_ide_version` at `26.39` if + you implement or consume `EmbeddingBackend`; an older IDE has no such type, and a + consumer's `instanceof` against it there fails to resolve the class. + ### 26.36 — unreleased - **added — Build provenance in every `.cgp`** _(ADFA-5394)_ **[verified]** A plugin artifact now records the commit it was built from, so a crash report or a diff --git a/docs/plugin-api.md b/docs/plugin-api.md index 3824834fb6..cfb2c97a18 100644 --- a/docs/plugin-api.md +++ b/docs/plugin-api.md @@ -12,7 +12,7 @@ The surface a plugin binds to is broader than one module. All of the following a - Core: `IPlugin` (lifecycle), `PluginContext`, `PluginLogger`, `ServiceRegistry`, `ResourceManager`. - Extension interfaces plugins **implement**: `UIExtension`, `EditorExtension`, `EditorTabExtension`, `DocumentationExtension`, `BuildActionExtension`, `SnippetExtension`, `ProjectExtension`, `FileOpenExtension`, `SettingsExtension`. - IDE service interfaces plugins **call** (via `ServiceRegistry.get(X::class.java)`): `IdeProjectService`, `IdeEditorService`, `IdeFileService`, `IdeEnvironmentService`, `IdeArchiveService`, `IdeBuildService`, `IdeUIService`, `IdeEditorTabService`, `IdeTooltipService`, `IdeThemeService`, `IdeFeatureFlagService`, `IdeCommandService`, `IdeTemplateService`, `IdeSnippetService`, `IdeSidebarService`. - - Cross-plugin service interfaces, where **one plugin implements what another calls** (via `SharedServices`): `LlmInferenceService` — implemented by ai-core, called by every AI plugin — together with the types nested in it that a *backend* plugin implements (`LlmBackend`, `HistoryCapableBackend`, `ToolCallingBackend`, `CancellableBackend`, `ConfigurableBackend`) and the value types either side constructs (`ChatMessage`, `LlmConfig`, `LlmResponse`, `SystemPromptRequest`, `ToolDefinition`, `ToolCallRequest`). Also `ToolSourceRegistry` — implemented by ai-core, called by any plugin contributing tools to the agent — with `ToolSource` and `ToolSpec`, which a *contributing* plugin implements, `ToolInvocation`, which ai-core constructs and passes to `ToolSource.invoke`, and `ToolOutcome`, which the source returns. + - Cross-plugin service interfaces, where **one plugin implements what another calls** (via `SharedServices`): `LlmInferenceService` — implemented by ai-core, called by every AI plugin — together with the types nested in it that a *backend* plugin implements (`LlmBackend`, `HistoryCapableBackend`, `ToolCallingBackend`, `CancellableBackend`, `ConfigurableBackend`, `EmbeddingBackend`) and the value types either side constructs (`ChatMessage`, `LlmConfig`, `LlmResponse`, `SystemPromptRequest`, `ToolDefinition`, `ToolCallRequest`). Also `ToolSourceRegistry` — implemented by ai-core, called by any plugin contributing tools to the agent — with `ToolSource` and `ToolSpec`, which a *contributing* plugin implements, `ToolInvocation`, which ai-core constructs and passes to `ToolSource.invoke`, and `ToolOutcome`, which the source returns. - Utility classes plugins **instantiate**: `KeystoreSecretStore` (AES/GCM over the Android Keystore, alias supplied by the caller). Host-side implementation rather than an interface, so plugins share one copy in the process instead of compiling their own. - Data classes plugins **construct** (e.g. `MenuItem`, `TabItem`, `EditorTabItem`, `NavigationItem`, `ToolbarAction`, `FabAction`, `PluginBuildAction`, `SnippetContribution`, `PluginTooltipEntry`, `PluginSettingsEntry`). - Enums / sealed types plugins **reference**: `PluginPermission`, `ShowAsAction`, `ArchiveFormat`, `BuildActionCategory`, `ToolbarActionIds`, `CommandSpec`, `CommandResult`, `ExtractResult`, `KeystoreSecretStore.Stored`. Sealed, so a plugin `when`s over the cases exhaustively — adding one is a **breaking** change, not an additive one. diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index 9e56ba7ee5..7e6a46af6f 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -1604,6 +1604,12 @@ public abstract interface class com/itsaky/androidide/plugins/services/LlmInfere public abstract fun getSettingsFragmentClassName ()Ljava/lang/String; } +public abstract interface class com/itsaky/androidide/plugins/services/LlmInferenceService$EmbeddingBackend : com/itsaky/androidide/plugins/services/LlmInferenceService$LlmBackend { + public abstract fun embed (Ljava/util/List;)Ljava/util/concurrent/CompletableFuture; + public abstract fun getEmbeddingDimensions ()I + public abstract fun getEmbeddingModelId ()Ljava/lang/String; +} + public abstract interface class com/itsaky/androidide/plugins/services/LlmInferenceService$HistoryCapableBackend : com/itsaky/androidide/plugins/services/LlmInferenceService$LlmBackend { public abstract fun generateStreamingWithHistory (Ljava/util/List;Ljava/lang/String;Lcom/itsaky/androidide/plugins/services/LlmInferenceService$LlmConfig;Lcom/itsaky/androidide/plugins/services/LlmInferenceService$StreamCallback;)V } diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java index f9cb3b5c8b..cf849f22f6 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java @@ -13,7 +13,7 @@ * Service for LLM inference operations. Provided by ai-core plugin. * *

- * {@link LlmBackend} is the one type here that plugins implement rather than call, so it carries only what every backend can answer. Anything a backend may or may not do is a separate interface extending it -- {@link HistoryCapableBackend}, {@link ToolCallingBackend}, {@link CancellableBackend}, {@link ConfigurableBackend} -- and the consumer asks with {@code instanceof} before it calls. A capability is therefore declared by the type, not by a flag a backend can set inconsistently with the methods it overrode. + * {@link LlmBackend} is the one type here that plugins implement rather than call, so it carries only what every backend can answer. Anything a backend may or may not do is a separate interface extending it -- {@link HistoryCapableBackend}, {@link ToolCallingBackend}, {@link CancellableBackend}, {@link ConfigurableBackend}, {@link EmbeddingBackend} -- and the consumer asks with {@code instanceof} before it calls. A capability is therefore declared by the type, not by a flag a backend can set inconsistently with the methods it overrode. */ public interface LlmInferenceService { @@ -102,6 +102,9 @@ void generateStreamingWithTools( /** * Generates embeddings for the given text. * + *

+ * Addresses a backend by id and returns a bare vector, so the caller learns neither which model produced it nor how long it is, and pays one round trip per text. {@link EmbeddingBackend} carries both and takes a batch; prefer it for anything a caller stores or repeats. This method stays because plugins already built against it call it. + * * @param text * the input text to embed (must not be null) * @param backendId @@ -251,6 +254,62 @@ interface ConfigurableBackend extends LlmBackend { String getSettingsFragmentClassName(); } + /** + * An {@link LlmBackend} that turns text into vectors. + * + *

+ * Implementing this is the declaration, exactly as with {@link ToolCallingBackend}: a backend that has no embedding model does not implement it, and the consumer asks with {@code instanceof} before it calls. Nothing here is reachable through {@link LlmInferenceService#getEmbeddings}, which addresses a backend by id and cannot report what produced the vector it returns. + * + *

+ * The batch is the unit of work, not a convenience over a single-text call. Indexing a project is thousands of chunks, and one round trip per chunk against a remote provider is the difference between a feature that finishes on a phone and one that does not. + * + *

+ * Failure contract. A batch completes whole or fails whole. The returned future either yields a list the same size as {@code texts}, positionally aligned with it, or completes exceptionally; it never yields a short list, a list padded with nulls, or a list holding a placeholder vector. A caller storing the result would otherwise persist entries it cannot tell apart from real ones, and a vector that is merely plausible never reports itself as wrong -- it just stops matching. + * + *

+ * Threading. {@link #embed} may be called from any thread and must not block the calling one: start the work and return the future. Implementations must be safe for concurrent calls, because indexing and a user's query can be in flight at once. {@link #getEmbeddingModelId} and {@link #getEmbeddingDimensions} are consulted on the caller's thread, so they answer from state the backend already holds rather than performing I/O. + * + *

+ * Errors. Neither accessor throws. {@link #embed} reports every failure -- transport, authentication, rate limiting, a model that rejected an input -- by completing the future exceptionally, and throws synchronously only for a caller's own mistake, {@link NullPointerException} for a null argument or element and {@link IllegalArgumentException} for an empty list. A consumer that cannot tell a failure from a refusal to start has to guard both paths at every call site. + */ + interface EmbeddingBackend extends LlmBackend { + + /** + * Embeds a batch of texts in one call. + * + * @param texts + * the texts to embed; must not be null, must not be empty, and must contain no null element + * @return a future yielding one vector per input, in input order, each of {@link #getEmbeddingDimensions} length -- or completed exceptionally, leaving the whole batch unproduced (never null) + * @throws IllegalArgumentException + * if {@code texts} is empty + * @throws NullPointerException + * if {@code texts} or any element of it is null + */ + @NonNull + CompletableFuture> embed(@NonNull List texts); + + /** + * Gets the number of components in every vector this backend produces. + * + *

+ * Constant for the lifetime of the backend instance, so a consumer may size its storage once. It is not on its own an identity: two unrelated models commonly share a width, and comparing their vectors yields a similarity that looks ordinary and means nothing. Pair it with {@link #getEmbeddingModelId} wherever provenance is recorded. + * + * @return the vector length, always positive + */ + int getEmbeddingDimensions(); + + /** + * Gets the stable identifier of the model producing these vectors, for example {@code "text-embedding-3-small"}. + * + *

+ * This is the model's identity, not the backend's -- {@link LlmBackend#getId} names the backend, and one backend may be reconfigured onto a different model without changing it. Vectors from two different models are incomparable whether or not their widths agree, so a consumer that persists vectors records this alongside them and reindexes when it changes. Without it a model swap silently degrades every stored vector instead of invalidating it. + * + * @return the embedding model identifier, never empty + */ + @NonNull + String getEmbeddingModelId(); + } + /** * An {@link LlmBackend} that renders earlier turns of a conversation. * diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java index 58ad49fb9a..099037189b 100644 --- a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java @@ -1,23 +1,45 @@ package com.itsaky.androidide.plugins.services; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.junit.Test; /** - * Covers the validating, coalescing and copying branches of the value types plugins construct. Every consumer of this jar is an out-of-tree plugin, so a constructor that accepts a bad state here surfaces as a runtime failure nothing in this repo compiles against. + * Covers the validating, coalescing and copying branches of the value types plugins construct, and the contracts a plugin implements rather than calls. Every consumer of this jar is an out-of-tree plugin, so a constructor that accepts a bad state here, or a capability interface that drifts, surfaces as a runtime failure nothing in this repo compiles against. */ public class LlmInferenceServiceTest { + /** + * Mirrors {@link HashingEmbeddingBackend}'s vector so a result can be traced back to the input that produced it. + */ + private static float[] expectedVector(String text, int dimensions) { + float[] vector = new float[dimensions]; + for (int i = 0; i < dimensions; i++) { + vector[i] = (text.hashCode() >> i) & 1; + } + return vector; + } + @Test public void chatMessageCarriesNoCorrelatorsForAConversationTurn() { LlmInferenceService.ChatMessage message = new LlmInferenceService.ChatMessage(LlmInferenceService.ChatMessage.Role.USER, "hello"); @@ -48,6 +70,120 @@ public void chatMessageRejectsAToolRoleWithoutCorrelators() { } } + @Test + public void embeddingBackendDeclaresItsCapabilityByTypeRatherThanByAFlag() { + LlmInferenceService.LlmBackend plain = new PlainBackend(); + LlmInferenceService.LlmBackend embedding = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + + assertFalse(plain instanceof LlmInferenceService.EmbeddingBackend); + assertTrue(embedding instanceof LlmInferenceService.EmbeddingBackend); + } + + @Test + public void embeddingBackendFailsTheWholeBatchRatherThanPartOfIt() throws Exception { + LlmInferenceService.EmbeddingBackend backend = new RefusingEmbeddingBackend(); + + CompletableFuture> future = backend.embed(Arrays.asList("first", "second")); + + try { + future.get(5, TimeUnit.SECONDS); + fail("expected ExecutionException"); + } catch (ExecutionException expected) { + // nothing is handed back, so a caller cannot store half a batch and mistake it for a whole one + assertTrue(expected.getCause() instanceof IOException); + } + } + + @Test + public void embeddingBackendIgnoresAMutationOfTheCallersListAfterTheCall() throws Exception { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + List texts = new ArrayList<>(Arrays.asList("alpha", "beta")); + + CompletableFuture> future = backend.embed(texts); + texts.clear(); + + List vectors = future.get(5, TimeUnit.SECONDS); + assertEquals(2, vectors.size()); + assertArrayEquals(expectedVector("alpha", 4), vectors.get(0), 0.0f); + assertArrayEquals(expectedVector("beta", 4), vectors.get(1), 0.0f); + } + + @Test + public void embeddingBackendKeepsConcurrentBatchesAligned() throws Exception { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + int batches = 32; + ExecutorService callers = Executors.newFixedThreadPool(4); + + try { + CountDownLatch start = new CountDownLatch(1); + List>> submitted = new ArrayList<>(batches); + for (int i = 0; i < batches; i++) { + String text = "chunk-" + i; + submitted.add(callers.submit(() -> { + start.await(); + return backend.embed(Collections.singletonList(text)).get(5, TimeUnit.SECONDS); + })); + } + start.countDown(); + + for (int i = 0; i < batches; i++) { + List vectors = submitted.get(i).get(10, TimeUnit.SECONDS); + assertEquals(1, vectors.size()); + assertArrayEquals(expectedVector("chunk-" + i, 4), vectors.get(0), 0.0f); + } + } finally { + callers.shutdownNow(); + } + } + + @Test + public void embeddingBackendNamesTheModelApartFromTheBackend() { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(1536, "text-embedding-3-small"); + + // two models of equal width are mutually incomparable, so the id is the part that detects a swap + assertEquals("hashing", backend.getId()); + assertEquals("text-embedding-3-small", backend.getEmbeddingModelId()); + assertEquals(1536, backend.getEmbeddingDimensions()); + } + + @Test + public void embeddingBackendRejectsAnEmptyBatchBeforeStartingWork() { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + + try { + backend.embed(Collections.emptyList()); + fail("expected IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + assertTrue(expected.getMessage().contains("texts")); + } + } + + @Test + public void embeddingBackendRejectsANullTextBeforeStartingWork() { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + + try { + backend.embed(Arrays.asList("alpha", null)); + fail("expected NullPointerException"); + } catch (NullPointerException expected) { + // thrown from the call, not the future, so a caller guards one path rather than two + } + } + + @Test + public void embeddingBackendReturnsOneVectorPerInputInInputOrder() throws Exception { + LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); + List texts = Arrays.asList("alpha", "beta", "gamma"); + + List vectors = backend.embed(texts).get(5, TimeUnit.SECONDS); + + assertEquals(texts.size(), vectors.size()); + for (int i = 0; i < texts.size(); i++) { + assertEquals(backend.getEmbeddingDimensions(), vectors.get(i).length); + assertArrayEquals(expectedVector(texts.get(i), 4), vectors.get(i), 0.0f); + } + } + @Test public void llmConfigRejectsAMissingBackendId() { try { @@ -157,4 +293,142 @@ public void toolResultRejectsAMissingCallId() { // without a call id the result cannot be matched to the call it answers } } + + /** + * A minimal conforming backend: stateless, so concurrent batches cannot interleave; validating before it starts any work; and copying the caller's list so a mutation after the call cannot reach the batch in flight. + */ + private static final class HashingEmbeddingBackend extends StubEmbeddingBackend { + + HashingEmbeddingBackend(int dimensions, String modelId) { + super("hashing", dimensions, modelId); + } + + @Override + public CompletableFuture> embed(List texts) { + List batch = new ArrayList<>(Objects.requireNonNull(texts, "texts")); + if (batch.isEmpty()) { + throw new IllegalArgumentException("texts must not be empty"); + } + for (String text : batch) { + Objects.requireNonNull(text, "texts must not contain a null element"); + } + int dimensions = getEmbeddingDimensions(); + return CompletableFuture.supplyAsync(() -> { + List vectors = new ArrayList<>(batch.size()); + for (String text : batch) { + vectors.add(expectedVector(text, dimensions)); + } + return Collections.unmodifiableList(vectors); + }); + } + } + + /** + * An {@link LlmInferenceService.LlmBackend} with no embedding capability, so the {@code instanceof} discrimination is exercised against a backend that really lacks it rather than against a mock. + */ + private static final class PlainBackend implements LlmInferenceService.LlmBackend { + + @Override + public CompletableFuture generate(String prompt, LlmInferenceService.LlmConfig config) { + return CompletableFuture.completedFuture(LlmInferenceService.LlmResponse.success("ok", 1, 1L)); + } + + @Override + public void generateStreaming(String prompt, LlmInferenceService.LlmConfig config, LlmInferenceService.StreamCallback callback) { + callback.onComplete(LlmInferenceService.LlmResponse.success("ok", 1, 1L)); + } + + @Override + public CompletableFuture generateWithHistory(List history, String prompt, LlmInferenceService.LlmConfig config) { + return generate(prompt, config); + } + + @Override + public String getId() { + return "plain"; + } + + @Override + public String getName() { + return "Plain"; + } + + @Override + public boolean isAvailable() { + return true; + } + } + + /** + * Reports a transport failure the documented way: the future completes exceptionally and yields no vector at all, not a short or padded list. + */ + private static final class RefusingEmbeddingBackend extends StubEmbeddingBackend { + + RefusingEmbeddingBackend() { + super("refusing", 4, "text-embedding-3-small"); + } + + @Override + public CompletableFuture> embed(List texts) { + CompletableFuture> future = new CompletableFuture<>(); + future.completeExceptionally(new IOException("embedding endpoint refused")); + return future; + } + } + + /** + * The {@link LlmInferenceService.LlmBackend} half of an embedding backend, which none of these tests exercise. Kept apart from the embedding behaviour so each double below says only what it is for. + */ + private abstract static class StubEmbeddingBackend implements LlmInferenceService.EmbeddingBackend { + + private final int dimensions; + private final String id; + private final String modelId; + + StubEmbeddingBackend(String id, int dimensions, String modelId) { + this.id = id; + this.dimensions = dimensions; + this.modelId = modelId; + } + + @Override + public CompletableFuture generate(String prompt, LlmInferenceService.LlmConfig config) { + return CompletableFuture.completedFuture(LlmInferenceService.LlmResponse.failure("not a generating backend")); + } + + @Override + public void generateStreaming(String prompt, LlmInferenceService.LlmConfig config, LlmInferenceService.StreamCallback callback) { + callback.onError("not a generating backend"); + } + + @Override + public CompletableFuture generateWithHistory(List history, String prompt, LlmInferenceService.LlmConfig config) { + return generate(prompt, config); + } + + @Override + public int getEmbeddingDimensions() { + return dimensions; + } + + @Override + public String getEmbeddingModelId() { + return modelId; + } + + @Override + public String getId() { + return id; + } + + @Override + public String getName() { + return id; + } + + @Override + public boolean isAvailable() { + return true; + } + } } From 534bb033207b5e692bb078b9a844ce27590631fc Mon Sep 17 00:00:00 2001 From: John Trujillo Date: Mon, 21 Sep 2026 16:19:41 -0500 Subject: [PATCH 2/5] ADFA-6053: Document that embed snapshots the caller batch The test pins that a mutation of the caller list after embed returns cannot reach the batch in flight, but the contract never required it. An implementation could retain the list and hand back a short or misaligned batch while still conforming. --- docs/PLUGIN_API_CHANGELOG.md | 4 +++- .../androidide/plugins/services/LlmInferenceService.java | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 0d38c10e61..d8d1938cbb 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -54,7 +54,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] The batch either completes whole or fails whole; it never yields a short list, a list padded with nulls, or a placeholder vector, so a caller can never store a partially-real batch. `embed` must not block the calling thread and must be safe for concurrent calls - (indexing and a user's query can be in flight at once); it reports every failure by + (indexing and a user's query can be in flight at once), and it snapshots the caller's + list before returning, so a caller may reuse or clear its own list as soon as the call + comes back. It reports every failure by completing the future exceptionally and throws synchronously only for a caller's own mistake — `NullPointerException` for a null argument or element, `IllegalArgumentException` for an empty list. diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java index cf849f22f6..46c90bd9df 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java @@ -278,7 +278,7 @@ interface EmbeddingBackend extends LlmBackend { * Embeds a batch of texts in one call. * * @param texts - * the texts to embed; must not be null, must not be empty, and must contain no null element + * the texts to embed; must not be null, must not be empty, and must contain no null element. The implementation snapshots the list before it returns, so a caller may reuse or clear its own list the moment the call comes back without disturbing the batch in flight. * @return a future yielding one vector per input, in input order, each of {@link #getEmbeddingDimensions} length -- or completed exceptionally, leaving the whole batch unproduced (never null) * @throws IllegalArgumentException * if {@code texts} is empty From fd5da77cdd1ec7d99a4f848c8112c77f17460141 Mon Sep 17 00:00:00 2001 From: John Trujillo Date: Tue, 22 Sep 2026 13:18:55 -0500 Subject: [PATCH 3/5] fix(plugin-api): ADFA-6053 file EmbeddingBackend under 26.40 and add requireValidBatch The helper gives backends one shared check and snapshot of the batch. The test now expects values that don't repeat past 32 components. --- docs/PLUGIN_API_CHANGELOG.md | 11 +++++---- plugin-api/api/plugin-api.api | 1 + .../plugins/services/LlmInferenceService.java | 23 +++++++++++++++++++ .../services/LlmInferenceServiceTest.java | 10 ++------ 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 6744105434..f1459ae8eb 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,7 +35,7 @@ need a source change, a recompile, or both · `tooling` = API-stability milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]** = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). -### 26.39 — unreleased +### 26.40 — unreleased - **added — An embedding capability a backend can declare** _(ADFA-6053)_ **[verified]** A backend that has an embedding model can now say so. The only embedding entry point before this was `LlmInferenceService.getEmbeddings(String, String)`, which addresses a @@ -59,11 +59,12 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] comes back. It reports every failure by completing the future exceptionally and throws synchronously only for a caller's own mistake — `NullPointerException` for a null argument or element, `IllegalArgumentException` - for an empty list. - Purely additive: a new interface with three new methods, nothing existing changed (the - ABI dump diff is six added lines and no removals), so an already-built `.cgp` keeps + for an empty list. The static `EmbeddingBackend.requireValidBatch(List)` does + those checks and returns the snapshot, so a backend calls it first in `embed`. + Purely additive: a new interface with three new methods and one static helper, nothing + existing changed (the ABI dump diff is seven added lines and no removals), so an already-built `.cgp` keeps loading and running against the refreshed jar. `getEmbeddings(String, String)` stays — - the Vector-Search plugin is a live caller. Floor `plugin.min_ide_version` at `26.39` if + the Vector-Search plugin is a live caller. Floor `plugin.min_ide_version` at `26.40` if you implement or consume `EmbeddingBackend`; an older IDE has no such type, and a consumer's `instanceof` against it there fails to resolve the class. diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index 7e6a46af6f..3ed7154a79 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -1608,6 +1608,7 @@ public abstract interface class com/itsaky/androidide/plugins/services/LlmInfere public abstract fun embed (Ljava/util/List;)Ljava/util/concurrent/CompletableFuture; public abstract fun getEmbeddingDimensions ()I public abstract fun getEmbeddingModelId ()Ljava/lang/String; + public static fun requireValidBatch (Ljava/util/List;)Ljava/util/List; } public abstract interface class com/itsaky/androidide/plugins/services/LlmInferenceService$HistoryCapableBackend : com/itsaky/androidide/plugins/services/LlmInferenceService$LlmBackend { diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java index 46c90bd9df..187d207c25 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java @@ -274,6 +274,29 @@ interface ConfigurableBackend extends LlmBackend { */ interface EmbeddingBackend extends LlmBackend { + /** + * Validates a batch against {@link #embed}'s synchronous contract and snapshots it, so every backend enforces the contract the same way. Call it first in {@code embed}, before starting any work. + * + * @param texts + * the batch as passed to {@link #embed} + * @return a copy of {@code texts} that later caller mutations cannot reach + * @throws IllegalArgumentException + * if {@code texts} is empty + * @throws NullPointerException + * if {@code texts} or any element of it is null + */ + @NonNull + static List requireValidBatch(List texts) { + List batch = new ArrayList<>(Objects.requireNonNull(texts, "texts")); + if (batch.isEmpty()) { + throw new IllegalArgumentException("texts must not be empty"); + } + for (String text : batch) { + Objects.requireNonNull(text, "texts must not contain a null element"); + } + return batch; + } + /** * Embeds a batch of texts in one call. * diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java index 099037189b..e8869910f5 100644 --- a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java @@ -35,7 +35,7 @@ public class LlmInferenceServiceTest { private static float[] expectedVector(String text, int dimensions) { float[] vector = new float[dimensions]; for (int i = 0; i < dimensions; i++) { - vector[i] = (text.hashCode() >> i) & 1; + vector[i] = Objects.hash(text, i) & 1; } return vector; } @@ -305,13 +305,7 @@ private static final class HashingEmbeddingBackend extends StubEmbeddingBackend @Override public CompletableFuture> embed(List texts) { - List batch = new ArrayList<>(Objects.requireNonNull(texts, "texts")); - if (batch.isEmpty()) { - throw new IllegalArgumentException("texts must not be empty"); - } - for (String text : batch) { - Objects.requireNonNull(text, "texts must not contain a null element"); - } + List batch = LlmInferenceService.EmbeddingBackend.requireValidBatch(texts); int dimensions = getEmbeddingDimensions(); return CompletableFuture.supplyAsync(() -> { List vectors = new ArrayList<>(batch.size()); From 931beef91e2390250998848c8bbd09132051ba49 Mon Sep 17 00:00:00 2001 From: John Trujillo Date: Tue, 22 Sep 2026 15:00:37 -0500 Subject: [PATCH 4/5] docs(plugin-api): ADFA-6053 split the 26.36 changelog bucket by release tag Date 26.36 and 26.37 from their tags, move ADFA-6189 to 26.40, add retag step. --- docs/PLUGIN_API_CHANGELOG.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index f1459ae8eb..f29df58121 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -67,8 +67,6 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] the Vector-Search plugin is a live caller. Floor `plugin.min_ide_version` at `26.40` if you implement or consume `EmbeddingBackend`; an older IDE has no such type, and a consumer's `instanceof` against it there fails to resolve the class. - -### 26.36 — unreleased - **added — `SnippetContribution.language` accepts `kotlin`** _(ADFA-6189)_ The host keys Kotlin snippets under `kt`, so a contribution declaring `kotlin` registered under a language nothing looks up and never appeared in a `.kt` file. The id is now @@ -76,6 +74,7 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] Accepted ids are `java`, `kt` (or `kotlin`) and `xml` — anything else registers but is never queried. +### 26.37 — 2026-09-08 - **added — Build provenance in every `.cgp`** _(ADFA-5394)_ **[verified]** A plugin artifact now records the commit it was built from, so a crash report or a support question can be traced back to source. Nothing in the pipeline carried a git @@ -130,6 +129,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] either state. Neither can be applied by the IDE on a plugin's behalf: `Window` has no theme attribute for its type, and a toast is posted by the system against whatever context built it. + +### 26.36 — 2026-09-01 - **added — File-targeted editor save** _(ADFA-5259)_ Save a named file's open buffer and find out whether the bytes actually landed. `saveCurrentFile` follows whichever tab the user has focused and returns as soon @@ -415,3 +416,6 @@ Map any commit to the release that first shipped it: ```bash git tag --list --contains | grep -E '^[0-9]{2}\.[0-9]{2}$' | sort -V | head -1 ``` + +When a release is tagged, replace its bucket's `unreleased` with the tag date and move +any entry the tag does not contain up to the next bucket. From 2f977a7d996191482c87caa75ced5cd00279b5ea Mon Sep 17 00:00:00 2001 From: John Trujillo Date: Tue, 22 Sep 2026 15:19:56 -0500 Subject: [PATCH 5/5] test(plugin-api): ADFA-6053 make the embed oracle tell inputs apart Keep 24 hash bits, validate in RefusingEmbeddingBackend, drop the concurrency test, document output ownership. --- docs/PLUGIN_API_CHANGELOG.md | 2 +- .../plugins/services/LlmInferenceService.java | 2 +- .../services/LlmInferenceServiceTest.java | 36 ++----------------- 3 files changed, 5 insertions(+), 35 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index f29df58121..9b79639203 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -56,7 +56,7 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] batch. `embed` must not block the calling thread and must be safe for concurrent calls (indexing and a user's query can be in flight at once), and it snapshots the caller's list before returning, so a caller may reuse or clear its own list as soon as the call - comes back. It reports every failure by + comes back; the caller owns the returned list and arrays outright. It reports every failure by completing the future exceptionally and throws synchronously only for a caller's own mistake — `NullPointerException` for a null argument or element, `IllegalArgumentException` for an empty list. The static `EmbeddingBackend.requireValidBatch(List)` does diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java index 187d207c25..0a34a333b4 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/LlmInferenceService.java @@ -302,7 +302,7 @@ static List requireValidBatch(List texts) { * * @param texts * the texts to embed; must not be null, must not be empty, and must contain no null element. The implementation snapshots the list before it returns, so a caller may reuse or clear its own list the moment the call comes back without disturbing the batch in flight. - * @return a future yielding one vector per input, in input order, each of {@link #getEmbeddingDimensions} length -- or completed exceptionally, leaving the whole batch unproduced (never null) + * @return a future yielding one vector per input, in input order, each of {@link #getEmbeddingDimensions} length -- or completed exceptionally, leaving the whole batch unproduced (never null). The caller owns the returned list and its arrays outright; the implementation must not retain or share them, for example from a cache. * @throws IllegalArgumentException * if {@code texts} is empty * @throws NullPointerException diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java index e8869910f5..4ff3f6b695 100644 --- a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/LlmInferenceServiceTest.java @@ -16,11 +16,7 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.junit.Test; @@ -35,7 +31,8 @@ public class LlmInferenceServiceTest { private static float[] expectedVector(String text, int dimensions) { float[] vector = new float[dimensions]; for (int i = 0; i < dimensions; i++) { - vector[i] = Objects.hash(text, i) & 1; + // low 24 bits so the int survives the float conversion exactly and inputs stay distinct + vector[i] = Objects.hash(text, i) & 0xFFFFFF; } return vector; } @@ -108,34 +105,6 @@ public void embeddingBackendIgnoresAMutationOfTheCallersListAfterTheCall() throw assertArrayEquals(expectedVector("beta", 4), vectors.get(1), 0.0f); } - @Test - public void embeddingBackendKeepsConcurrentBatchesAligned() throws Exception { - LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(4, "text-embedding-3-small"); - int batches = 32; - ExecutorService callers = Executors.newFixedThreadPool(4); - - try { - CountDownLatch start = new CountDownLatch(1); - List>> submitted = new ArrayList<>(batches); - for (int i = 0; i < batches; i++) { - String text = "chunk-" + i; - submitted.add(callers.submit(() -> { - start.await(); - return backend.embed(Collections.singletonList(text)).get(5, TimeUnit.SECONDS); - })); - } - start.countDown(); - - for (int i = 0; i < batches; i++) { - List vectors = submitted.get(i).get(10, TimeUnit.SECONDS); - assertEquals(1, vectors.size()); - assertArrayEquals(expectedVector("chunk-" + i, 4), vectors.get(0), 0.0f); - } - } finally { - callers.shutdownNow(); - } - } - @Test public void embeddingBackendNamesTheModelApartFromTheBackend() { LlmInferenceService.EmbeddingBackend backend = new HashingEmbeddingBackend(1536, "text-embedding-3-small"); @@ -364,6 +333,7 @@ private static final class RefusingEmbeddingBackend extends StubEmbeddingBackend @Override public CompletableFuture> embed(List texts) { + LlmInferenceService.EmbeddingBackend.requireValidBatch(texts); CompletableFuture> future = new CompletableFuture<>(); future.completeExceptionally(new IOException("embedding endpoint refused")); return future;