package p.studio.app.lsp; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import p.studio.api.automation.*; import p.studio.app.operation.ExecutorOperationExecutor; import p.studio.core.language.*; import p.studio.core.project.*; import p.studio.core.session.DefaultAutomationSession; import p.studio.app.compiler.CompilerProjectKnowledge; import p.studio.lsp.api.LspServerLifecycle; import p.studio.lsp.messages.*; import p.studio.lsp.services.protocol.ExternalSourceLanguageServer; import org.eclipse.lsp4j.*; import org.eclipse.lsp4j.jsonrpc.*; import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; import java.net.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.jupiter.api.Assertions.*; /** Controlled protocol faults use real sockets; the stubborn child is an explicitly injected port. */ @org.junit.jupiter.api.Tag("integration") class LanguageFailureContractTest { @TempDir Path root; @Test void protocolMechanismsBecomeNeutralFailuresAndLegacyFallbackStaysLimited() throws Exception { root = root.toRealPath(); var json = new ObjectMapper(); Files.writeString(root.resolve("prometeu.json"), "{\"name\":\"fault\",\"version\":\"1\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}"); var source = Files.createDirectories(root.resolve("src")).resolve("main.pbs"); Files.writeString(source, "fn x() -> int { return 1; }\n"); var access = new ProjectAccessRegistry(); var catalog = new ProjectCatalogService(root.getParent(), json, new ProjectLocalStudioSetupStore(json)); var knowledge = new CompilerProjectKnowledge(access, catalog, json); var faults = new LinkedHashMap(); faults.put(-32020, AutomationFailure.Code.LANGUAGE_QUERY_REVISION_MISMATCH); faults.put(-32603, AutomationFailure.Code.LANGUAGE_QUERY_INTERNAL_FAILURE); faults.put(-32099, AutomationFailure.Code.LANGUAGE_QUERY_PROTOCOL_FAILURE); faults.put(0, AutomationFailure.Code.LANGUAGE_QUERY_TIMEOUT); faults.put(1, null); // controlled standard-only server try (var threads = Executors.newCachedThreadPool()) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(threads)); var registration = access.register(root, authority::enterManual, () -> true, authority); authority.grant(false).toCompletableFuture().join(); var task = authority.acquire().task(); try { for (var fault : faults.entrySet()) try (var listener = new ServerSocket(0, 8, InetAddress.getLoopbackAddress())) { var served = threads.submit(() -> { try (var socket = listener.accept()) { var clientRef = new AtomicReference(); var text = (org.eclipse.lsp4j.services.TextDocumentService)java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{org.eclipse.lsp4j.services.TextDocumentService.class}, (proxy, method, args) -> { if (method.getName().equals("didOpen")) { var open = (DidOpenTextDocumentParams)args[0]; clientRef.get().publishDiagnostics(new PublishDiagnosticsParams(open.getTextDocument().getUri(), List.of())); } return null; }); var server = (ExternalSourceLanguageServer)java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ExternalSourceLanguageServer.class}, (proxy, method, args) -> switch (method.getName()) { case "initialize" -> fault.getKey() == 0 ? new CompletableFuture() : fault.getKey() == 1 ? CompletableFuture.completedFuture(new InitializeResult(legacyCapabilities())) : CompletableFuture.failedFuture(new ResponseErrorException(new ResponseError(fault.getKey(), "controlled protocol failure", null))); case "getTextDocumentService" -> text; case "getWorkspaceService" -> new p.studio.lsp.services.protocol.PrometeuWorkspaceService(); default -> null; }); var launcher = new Launcher.Builder().setLocalService(server) .setRemoteInterface(org.eclipse.lsp4j.services.LanguageClient.class).setInput(socket.getInputStream()).setOutput(socket.getOutputStream()).setExecutorService(threads).create(); clientRef.set(launcher.getRemoteProxy()); launcher.startListening().get(5, TimeUnit.SECONDS); } catch (Exception ended) { /* Closing the client ends this controlled server. */ } }); var endpoint = new LspServerEndpoint(InetAddress.getLoopbackAddress().getHostAddress(), listener.getLocalPort()); var lifecycle = lifecycle(endpoint); var queries = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle, catalog, knowledge, json), 700, 500); var params = Map.of("uri", source.toUri().toString()); if (fault.getValue() == null) { var reply = queries.query(root, task.value(), "diagnostics", params); assertTrue(reply.get("limitations").toString().contains("ANALYSIS_DETAILS_UNAVAILABLE")); assertTrue(reply.get("analysis").toString().contains("not-evaluated")); } else { var failure = assertThrows(AutomationException.class, () -> queries.query(root, task.value(), "diagnostics", params)).failure(); assertEquals(fault.getValue(), failure.code()); assertTrue(failure.runtimeError().isEmpty()); assertEquals(true, failure.details().get("workerTerminated")); assertNotNull(failure.details().get("queryId")); } served.get(3, TimeUnit.SECONDS); } var missing = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle(null), catalog, knowledge, json)); assertEquals(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, assertThrows(AutomationException.class, () -> missing.query(root, task.value(), "diagnostics", Map.of("uri", source.toUri().toString()))).failure().code()); } finally { authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.unsubscribe(); } } } @Test void cancellationAndCleanupFailuresHaveSeparateNeutralCodes() throws Exception { try (var workers = Executors.newCachedThreadPool()) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(workers)); var access = new ProjectAccessRegistry(); var registration = access.register(root, authority::enterManual, () -> true, authority); authority.grant(false).toCompletableFuture().join(); var task = authority.acquire().task(); try { for (boolean cleanupFailure : List.of(false, true)) { var port = new LanguageQueryPort() { public void endTask(TaskIdentity identity) {} public Map query(TaskIdentity identity, String operation, Map parameters) { throw new AssertionError(); } public Map query(TaskIdentity identity, String operation, Map parameters, LanguageQueryExecution execution) { if (!cleanupFailure) throw new CancellationException("controlled cancellation"); execution.own(() -> { throw new IllegalStateException("controlled cleanup failure"); }); execution.cancel(); return Map.of(); } }; var queries = new TaskLanguageQueries(access, port); var error = assertThrows(AutomationException.class, () -> queries.query(root, task.value(), "diagnostics", Map.of())).failure(); assertEquals(cleanupFailure ? AutomationFailure.Code.LANGUAGE_QUERY_CLEANUP_FAILED : AutomationFailure.Code.LANGUAGE_QUERY_CANCELLED, error.code()); assertEquals(true, error.details().get("workerTerminated")); if (cleanupFailure) assertEquals("failed", error.details().get("cleanup")); assertEquals(ControlState.AGENT_WORKING, authority.snapshot().state()); } } finally { authority.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS); registration.unsubscribe(); } } } static ServerCapabilities legacyCapabilities() { var capabilities = new ServerCapabilities(); capabilities.setTextDocumentSync(TextDocumentSyncKind.Full); return capabilities; } static LspServerLifecycle lifecycle(LspServerEndpoint endpoint) { return new LspServerLifecycle() { public void bootServer(LspServerConfiguration config, LspProjectContext context) {} public void shutdownServer(LspProjectContext context) {} public Optional endpoint(LspProjectContext context) { return Optional.ofNullable(endpoint); } }; } @Test void delayedChildCleanupKeepsAdmissionAndPrimaryFailureUntilActualTermination() throws Exception { try (var threads = Executors.newCachedThreadPool()) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(threads)); var access = new ProjectAccessRegistry(); var registration = access.register(root, authority::enterManual, () -> true, authority); authority.grant(false).toCompletableFuture().join(); var task = authority.acquire().task(); var childEntered = new CountDownLatch(1); var releaseChild = new CountDownLatch(1); var executionRef = new AtomicReference(); var port = new LanguageQueryPort() { public Map query(TaskIdentity task, String operation, Map parameters) { throw new AssertionError(); } public void endTask(TaskIdentity task) {} public Map query(TaskIdentity task, String operation, Map parameters, LanguageQueryExecution execution) { executionRef.set(execution); var child = Executors.newSingleThreadExecutor(); child.submit(() -> { childEntered.countDown(); boolean interrupted = false; while (true) try { releaseChild.await(); break; } catch (InterruptedException ignored) { interrupted = true; } if (interrupted) Thread.currentThread().interrupt(); }); try { assertTrue(childEntered.await(2, TimeUnit.SECONDS)); } catch (InterruptedException stopped) { Thread.currentThread().interrupt(); } execution.own(child::shutdownNow); execution.finishWorkers(child); execution.record(AutomationFailure.Code.LANGUAGE_QUERY_INTERNAL_FAILURE, "late failure", Map.of()); return Map.of("late", true); } }; try { var queries = new TaskLanguageQueries(access, port, 150, 150); var call = threads.submit(() -> queries.query(root, task.value(), "diagnostics", Map.of())); assertTrue(childEntered.await(2, TimeUnit.SECONDS)); var error = assertInstanceOf(AutomationException.class, assertThrows(ExecutionException.class, () -> call.get(2, TimeUnit.SECONDS)).getCause()).failure(); assertEquals(AutomationFailure.Code.LANGUAGE_QUERY_TIMEOUT, error.code()); assertEquals(false, error.details().get("workerTerminated")); assertEquals(ControlResult.Status.BUSY, assertThrows(ControlDeniedException.class, () -> authority.submit(task, "successor", () -> null)).status()); assertEquals(ControlState.AGENT_WORKING, authority.snapshot().state()); releaseChild.countDown(); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); while (authority.snapshot().operation().state() != p.studio.api.operation.OperationState.CANCELLED && System.nanoTime() < deadline) Thread.onSpinWait(); assertEquals(AutomationFailure.Code.LANGUAGE_QUERY_TIMEOUT, executionRef.get().exception(AutomationFailure.Code.LANGUAGE_QUERY_INTERNAL_FAILURE, "later", true).failure().code()); } finally { releaseChild.countDown(); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.unsubscribe(); } } } }