Skip to content

Testing, Error Handling & Troubleshooting ​

Verification patterns for deterministic offline testing, Spring Boot test slicing, exception handling across all modules, and common production diagnostics.


1. Deterministic Offline Unit Testing (Zero API Keys) ​

dev.openhusky.ai.provider.LlmProvider is a @FunctionalInterface. Replace network providers with a scripted lambda in JUnit 5 tests to verify tool execution order, PermissionPolicy, HITL approvals, mid-run steer(), and context compaction in milliseconds with zero network calls:

java
import dev.openhusky.ai.model.ChatResponse;
import dev.openhusky.ai.model.ContentBlock;
import dev.openhusky.ai.model.Message;
import dev.openhusky.ai.model.ModelSpec;
import dev.openhusky.ai.model.StopReason;
import dev.openhusky.ai.model.StreamEvent;
import dev.openhusky.ai.model.TokenUsage;
import dev.openhusky.ai.provider.LlmProvider;
import dev.openhusky.core.policy.PermissionPolicy;
import dev.openhusky.core.runtime.AgentRuntime;
import dev.openhusky.core.runtime.AgentSession;
import dev.openhusky.core.runtime.RunResult;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;

AtomicInteger step = new AtomicInteger(0);
LlmProvider scripted = (req, signal, onEvent) -> {
    if (step.getAndIncrement() == 0) {
        var call = new ContentBlock.ToolCallBlock(
                "tc-1", "lookup_order", "{\"orderId\":\"#1042\"}");
        var msg = new Message.AssistantMessage(
                List.of(call), StopReason.TOOL_USE, TokenUsage.ZERO, Map.of());
        return new ChatResponse(msg, StopReason.TOOL_USE, TokenUsage.ZERO, req.model().id());
    }
    onEvent.accept(new StreamEvent.TextDelta("Order #1042 arrives tomorrow at 14:00."));
    var msg = Message.AssistantMessage.text("Order #1042 arrives tomorrow at 14:00.");
    return new ChatResponse(msg, StopReason.END_TURN, TokenUsage.ZERO, req.model().id());
};

try (AgentRuntime runtime = AgentRuntime.builder()
        .provider(scripted)
        .model(ModelSpec.custom("mock-model", 128_000, 4_096))
        .toolsFrom(new OrderTools())
        .permissionPolicy(PermissionPolicy.readOnly())
        .build()) {

    AgentSession session = runtime.openSession();
    RunResult result = session.prompt("Where is order #1042?");
    assertEquals("Order #1042 arrives tomorrow at 14:00.", result.finalText());
    assertEquals(2, result.stepsExecuted());
}

Testing Mid-Run Steering & HITL Deterministically ​

For steer() or ApprovalDecision.Handler tests, synchronize with a CountDownLatch:

  1. Have the scripted LlmProvider (or tool method) signal a CountDownLatch once inside step 1 or inside a SEQUENTIAL tool.
  2. From the test thread, call session.steer("Change direction") or resolve the approval broker, then release the latch.
  3. Assert that AgentEvent.SteeringApplied was emitted and the subsequent ChatRequest.messages() contains the synthesized skipped ToolResultBlocks followed by the steering UserMessage.

2. Testing Spring Boot Integrations ​

Auto-Configuration Slicing (ApplicationContextRunner) ​

Use Spring Boot's ApplicationContextRunner with a scripted LlmProvider bean to verify @OpenHuskyTools, AgentRuntimeCustomizer, and AOP proxy execution (such as @Aspect or @Transactional):

java
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(OpenHuskyAutoConfiguration.class));

@Test
void executesAopProxiedToolBean() {
    LlmProvider scripted = (req, sig, onEvent) -> ...;

    contextRunner
            .withPropertyValues("openhusky.permissions.mode=ALLOW_ALL")
            .withBean(LlmProvider.class, () -> scripted)
            .withUserConfiguration(ProxiedToolsConfig.class) // @EnableAspectJAutoProxy + @OpenHuskyTools
            .run(context -> {
                AgentRuntime runtime = context.getBean(AgentRuntime.class);
                RunResult result = runtime.openSession("s-1", Principal.of("u1")).prompt("Run tool");
                assertThat(result.finalText()).isEqualTo("done");
            });
}

Testing AG-UI Spring MVC Streaming (WebApplicationContextRunner + MockMvc) ​

Because OpenHuskyAgUiMvcController.run(...) returns an asynchronous SseEmitter backed by a virtual thread, assert request().asyncStarted() and unwrap via asyncDispatch(...) in MockMvc:

java
private final WebApplicationContextRunner webContextRunner = new WebApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(
                DispatcherServletAutoConfiguration.class,
                WebMvcAutoConfiguration.class,
                OpenHuskyAutoConfiguration.class,
                OpenHuskyAgUiAutoConfiguration.class,
                OpenHuskyAgUiMvcAutoConfiguration.class
        ));

@Test
void streamsSseEventsThroughMvcController() throws Exception {
    webContextRunner
            .withPropertyValues("openhusky.agui.mvc.allow-anonymous=true")
            .withBean(LlmProvider.class, () -> scriptedProvider)
            .run(context -> {
                MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
                MvcResult mvcResult = mockMvc.perform(post("/agui/run")
                                .contentType(MediaType.APPLICATION_JSON)
                                .content("{\"threadId\":\"t1\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}"))
                        .andExpect(request().asyncStarted())
                        .andReturn();

                mockMvc.perform(asyncDispatch(mvcResult))
                        .andExpect(status().isOk())
                        .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_EVENT_STREAM));
            });
}

3. Complete Exception Hierarchy Reference ​

All OpenHusky runtime exceptions are unchecked (RuntimeException) and organized cleanly by layer:

ModuleException ClassParentRetryable?When Thrown & Recommended Handling
openhusky-aiLlmExceptionRuntimeExceptionVaries (isRetryable())Root LLM transport/provider exception carrying providerId(), statusCode(), responseBody().
openhusky-aiRateLimitExceptionLlmExceptionYes (true)HTTP 429; exposes optional retryAfter() Duration. Handled by RetryInterceptor and FallbackProvider.
openhusky-aiTransientLlmExceptionLlmExceptionYes (true)HTTP 408, 425, 5xx, 529, I/O timeouts, or empty stream. Handled by RetryInterceptor and FallbackProvider.
openhusky-aiAuthExceptionLlmExceptionNo (false)HTTP 401 / 403 from upstream LLM API. Never retried on the same key; triggers FallbackProvider failover to another route.
openhusky-aiInvalidRequestExceptionLlmExceptionNo (false)Remaining HTTP 4xx request errors (malformed schema, invalid model parameter). Fix request payload.
openhusky-aiContextOverflowExceptionLlmExceptionNo (false)HTTP 400 / 413 / 422 matching ContextOverflowDetector patterns. Intercepted automatically by AgentLoop for EMERGENCY compaction + 1 retry.
openhusky-aiAbortSignal.AbortedExceptionRuntimeExceptionNoCooperative cancellation via AbortSignal.abort(...) or session.abort(...).
openhusky-sessionSessionExceptionRuntimeException—Root storage/projection failure (duplicate session ID, SQLite I/O error, closed store).
openhusky-sessionSessionCorruptionExceptionSessionException—Malformed JSONL/payload, missing required fields, or unsafe sessionId (.., /, \, control chars).
openhusky-sessionSessionFormatExceptionSessionException—Persisted session version > SessionHeader.CURRENT_FORMAT_VERSION (fail-closed version gate).
openhusky-coreSessionAccessDeniedExceptionRuntimeException—Caller Principal violated SessionAccessPolicy (TENANT_ISOLATED / PRINCIPAL_ISOLATED). Map to HTTP 403 Forbidden.
openhusky-coreStructuredOutputExceptionRuntimeException—promptStructured(...) exhausted maxValidationRetries or terminated early. Inspect rawText() and runResult().
openhusky-aguiAgUiAuthExceptionRuntimeException—Thrown by AgUiHttpPrincipalResolver / SpringAgUiPrincipalResolver; carries statusCode() (401 or 403).
openhusky-mcpMcpExceptionRuntimeException—MCP protocol, stdio process, JSON-RPC, or HTTP failure carrying optional jsonRpcCode(), httpStatus(), wwwAuthenticate().
openhusky-sandboxSandboxExceptionRuntimeException—Path jail violation, binary/oversized read, LocalOsSandbox unavailable under FAIL_CLOSED, or container failure.
openhusky-skillsSkillExceptionRuntimeException—Invalid SKILL.md frontmatter, path traversal, binary resource read, or strict(true) load failure.

4. Troubleshooting FAQ ​

Parameter name unavailable for @Tool method ... compile with -parameters ​

  • Cause: AnnotatedToolScanner / SpringAnnotatedToolScanner uses Parameter.isNamePresent() when @ToolParam(name = "...") is omitted. By default, javac strips method parameter names into arg0, arg1.
  • Fix: Enable <parameters>true</parameters> in maven-compiler-plugin (or -parameters in Gradle JavaCompile), or specify @ToolParam(name = "explicitName") on every parameter.

UnsupportedClassVersionError: class file version 65.0 ​

  • Cause: Running an application compiled with JDK 21 on an older JRE (e.g., JDK 17 = class version 61.0).
  • Fix: Ensure runtime java -version and JAVA_HOME point to JDK 21 LTS or newer.

Spring MVC /agui/run Returns 404 or Bean Missing on Startup ​

  • Cause: OpenHuskyAgUiMvcAutoConfiguration is fail-closed and activates OpenHuskyAgUiMvcController only when a SpringAgUiPrincipalResolver bean is registered or openhusky.agui.mvc.allow-anonymous=true is explicitly configured.
  • Fix: Register a @Bean SpringAgUiPrincipalResolver authenticating requests into Principal.of(userId, tenantId) (recommended), or set openhusky.agui.mvc.allow-anonymous=true for local development.

401 Unauthorized / 403 Forbidden / SessionAccessDeniedException ​

  • Cause: A session created under Principal.of("alice", "tenant-a") was accessed with a different tenantId (under TENANT_ISOLATED) or a different principalId (under PRINCIPAL_ISOLATED), or AgUiHttpPrincipalResolver returned null.
  • Fix: Verify the resolved Principal matches the owning session's tenantId (and principalId if PRINCIPAL_ISOLATED), or use separate threadIds per tenant/user.

NoUniqueBeanDefinitionException or Missing Auto-Configured AgentRuntime ​

  • Cause: Declaring multiple AgentRuntime, LlmProvider, or AgUiRunner beans without @Primary or explicit @Qualifier injection.
  • Fix: When running multiple distinct agents in one Spring Boot app, declare named @Beans (@Qualifier("shopRuntime"), @Qualifier("supportRuntime")), inject them by @Qualifier, and note that OpenHuskyAgUiAutoConfiguration backs off automatically when multiple AgentRuntime candidates exist (@ConditionalOnSingleCandidate).

LocalOsSandbox Throws OS sandbox unavailable (no bwrap or sandbox-exec detected) ​

  • Cause: LocalOsSandbox runs a startup probe for bwrap (Linux) or /usr/bin/sandbox-exec (macOS) and enforces FallbackPolicy.FAIL_CLOSED by default.
  • Fix: Install bubblewrap (apt install bubblewrap / dnf install bubblewrap) on Linux, use DockerSandbox (Tier L3) in unprivileged containers where user namespaces are disabled, or explicitly configure LocalHostSandbox (Tier L1) / .fallbackPolicy(FallbackPolicy.ALLOW_HOST_FALLBACK) when host-level execution is acceptable.

ContextOverflowException on Large Histories ​

  • Cause: A single step's system prompt + tool schemas + uncompacted tail exceeded the model's context window even after PROACTIVE and EMERGENCY compaction.
  • Fix: Verify ModelSpec.contextWindow() matches the real upstream model limit (especially for ModelSpec.custom(...) or openhusky.provider.context-window), enable OutputOffloadToolInterceptor (default 32_768 chars) so single tool calls cannot blow past the window, and keep ContextPipeline.withDefaultCompactor() active.

Released under the MIT License. Built with Java 21 Virtual Threads.