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:
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:
- Have the scripted
LlmProvider(or tool method) signal aCountDownLatchonce inside step 1 or inside aSEQUENTIALtool. - From the test thread, call
session.steer("Change direction")or resolve the approval broker, then release the latch. - Assert that
AgentEvent.SteeringAppliedwas emitted and the subsequentChatRequest.messages()contains the synthesized skippedToolResultBlocks followed by the steeringUserMessage.
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):
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:
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:
| Module | Exception Class | Parent | Retryable? | When Thrown & Recommended Handling |
|---|---|---|---|---|
openhusky-ai | LlmException | RuntimeException | Varies (isRetryable()) | Root LLM transport/provider exception carrying providerId(), statusCode(), responseBody(). |
openhusky-ai | RateLimitException | LlmException | Yes (true) | HTTP 429; exposes optional retryAfter() Duration. Handled by RetryInterceptor and FallbackProvider. |
openhusky-ai | TransientLlmException | LlmException | Yes (true) | HTTP 408, 425, 5xx, 529, I/O timeouts, or empty stream. Handled by RetryInterceptor and FallbackProvider. |
openhusky-ai | AuthException | LlmException | No (false) | HTTP 401 / 403 from upstream LLM API. Never retried on the same key; triggers FallbackProvider failover to another route. |
openhusky-ai | InvalidRequestException | LlmException | No (false) | Remaining HTTP 4xx request errors (malformed schema, invalid model parameter). Fix request payload. |
openhusky-ai | ContextOverflowException | LlmException | No (false) | HTTP 400 / 413 / 422 matching ContextOverflowDetector patterns. Intercepted automatically by AgentLoop for EMERGENCY compaction + 1 retry. |
openhusky-ai | AbortSignal.AbortedException | RuntimeException | No | Cooperative cancellation via AbortSignal.abort(...) or session.abort(...). |
openhusky-session | SessionException | RuntimeException | — | Root storage/projection failure (duplicate session ID, SQLite I/O error, closed store). |
openhusky-session | SessionCorruptionException | SessionException | — | Malformed JSONL/payload, missing required fields, or unsafe sessionId (.., /, \, control chars). |
openhusky-session | SessionFormatException | SessionException | — | Persisted session version > SessionHeader.CURRENT_FORMAT_VERSION (fail-closed version gate). |
openhusky-core | SessionAccessDeniedException | RuntimeException | — | Caller Principal violated SessionAccessPolicy (TENANT_ISOLATED / PRINCIPAL_ISOLATED). Map to HTTP 403 Forbidden. |
openhusky-core | StructuredOutputException | RuntimeException | — | promptStructured(...) exhausted maxValidationRetries or terminated early. Inspect rawText() and runResult(). |
openhusky-agui | AgUiAuthException | RuntimeException | — | Thrown by AgUiHttpPrincipalResolver / SpringAgUiPrincipalResolver; carries statusCode() (401 or 403). |
openhusky-mcp | McpException | RuntimeException | — | MCP protocol, stdio process, JSON-RPC, or HTTP failure carrying optional jsonRpcCode(), httpStatus(), wwwAuthenticate(). |
openhusky-sandbox | SandboxException | RuntimeException | — | Path jail violation, binary/oversized read, LocalOsSandbox unavailable under FAIL_CLOSED, or container failure. |
openhusky-skills | SkillException | RuntimeException | — | 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/SpringAnnotatedToolScannerusesParameter.isNamePresent()when@ToolParam(name = "...")is omitted. By default,javacstrips method parameter names intoarg0,arg1. - Fix: Enable
<parameters>true</parameters>inmaven-compiler-plugin(or-parametersin GradleJavaCompile), 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 -versionandJAVA_HOMEpoint to JDK 21 LTS or newer.
Spring MVC /agui/run Returns 404 or Bean Missing on Startup
- Cause:
OpenHuskyAgUiMvcAutoConfigurationis fail-closed and activatesOpenHuskyAgUiMvcControlleronly when aSpringAgUiPrincipalResolverbean is registered oropenhusky.agui.mvc.allow-anonymous=trueis explicitly configured. - Fix: Register a
@Bean SpringAgUiPrincipalResolverauthenticating requests intoPrincipal.of(userId, tenantId)(recommended), or setopenhusky.agui.mvc.allow-anonymous=truefor local development.
401 Unauthorized / 403 Forbidden / SessionAccessDeniedException
- Cause: A session created under
Principal.of("alice", "tenant-a")was accessed with a differenttenantId(underTENANT_ISOLATED) or a differentprincipalId(underPRINCIPAL_ISOLATED), orAgUiHttpPrincipalResolverreturnednull. - Fix: Verify the resolved
Principalmatches the owning session'stenantId(andprincipalIdifPRINCIPAL_ISOLATED), or use separatethreadIds per tenant/user.
NoUniqueBeanDefinitionException or Missing Auto-Configured AgentRuntime
- Cause: Declaring multiple
AgentRuntime,LlmProvider, orAgUiRunnerbeans without@Primaryor explicit@Qualifierinjection. - Fix: When running multiple distinct agents in one Spring Boot app, declare named
@Beans (@Qualifier("shopRuntime"),@Qualifier("supportRuntime")), inject them by@Qualifier, and note thatOpenHuskyAgUiAutoConfigurationbacks off automatically when multipleAgentRuntimecandidates exist (@ConditionalOnSingleCandidate).
LocalOsSandbox Throws OS sandbox unavailable (no bwrap or sandbox-exec detected)
- Cause:
LocalOsSandboxruns a startup probe forbwrap(Linux) or/usr/bin/sandbox-exec(macOS) and enforcesFallbackPolicy.FAIL_CLOSEDby default. - Fix: Install
bubblewrap(apt install bubblewrap/dnf install bubblewrap) on Linux, useDockerSandbox(Tier L3) in unprivileged containers where user namespaces are disabled, or explicitly configureLocalHostSandbox(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
PROACTIVEandEMERGENCYcompaction. - Fix: Verify
ModelSpec.contextWindow()matches the real upstream model limit (especially forModelSpec.custom(...)oropenhusky.provider.context-window), enableOutputOffloadToolInterceptor(default32_768chars) so single tool calls cannot blow past the window, and keepContextPipeline.withDefaultCompactor()active.