DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

DZone Spotlight

Saturday, December 5 View All Articles »
Keeping AI Code Generation Honest: A Deterministic Control Plane for Multi-Agent LLM Workflows

Keeping AI Code Generation Honest: A Deterministic Control Plane for Multi-Agent LLM Workflows

By Janani Annur Thiruvengadam DZone Core CORE
The Problem With Letting the Model Decide If you've tried to automate code generation with an LLM agent, you've probably hit this failure mode: the agent correctly handles all 10 steps of a task on Monday, then silently skips 3 of them on Tuesday for a nearly identical task. Nothing crashes. The output looks plausible. The gap only surfaces in review — or worse, in production. This is the core tension in agentic code generation. LLMs are excellent at the creative work (reading a spec, writing plausible code) and unreliable at the procedural work (always running every check, never skipping a gate, stopping after N retries instead of looping forever). When you hand both responsibilities to the same agent, the procedural guarantees are only as good as the model's mood that day. Our team builds data pipeline modules on a config-driven compute platform. Each new module — a cost forecast, a volume estimate, a revenue allocation — follows the same skeleton: load tables, apply joins, compute formulas, write outputs. Roughly 60% of the work is predictable boilerplate, and it was eating 2–4 weeks of engineering time per module. Perfect candidate for AI automation. But we weren't willing to trade weeks of engineering for a pipeline that quietly drops a null check. The solution wasn't a smarter prompt. It was moving all the guarantees out of the agent and into deterministic code. The Architecture: Control Plane vs. Knowledge Plane We split the system into two layers that are deliberately kept separate: The control plane is a plain Python state machine. It owns what runs next and whether it's allowed to proceed. It advances a task through a fixed sequence of gates, dispatches the right agent at each gate, counts retries, escalates to a human after a fixed budget, and persists state to disk so a run survives across sessions. Critically, it never writes production code and never publishes anything. It prints the next gated step plus a ready-to-dispatch prompt, records the result, and moves the marker. The knowledge plane is a set of skill files (structured markdown) that teach the agents how to do each step well — the architecture patterns, the validation checklist, the edge cases to watch for. The division of labor is the whole point: The control plane decides what runs and whether it passed. The skill files decide how it's done well. When the two disagree, the control plane wins. Because gate order, retry budget, and escalation live in code — not in a prompt the model can reinterpret — agent behavior becomes predictable, auditable, and structurally unable to skip a step. The Gate Sequence Every module moves through a fixed pipeline: input → analyzed → user-confirmed → generated → validated → tested → dq-ready → cr-ready → done The state machine enforces this order. An agent cannot jump from generated straight to done. It cannot reach validated without having produced something at generated. The gates are the contract, and the contract is executable. Let me walk through the interesting gates. Grounding Before Planning (input → analyzed) The first agent — the Analyzer — takes the uploaded logic (a spec, a SQL script, a spreadsheet of formulas) and produces a structured execution plan: every input table, every transformation, every null check, every conditional branch. But before it plans anything, it grounds itself against reality. For every table the logic references, it makes a read-only metadata call to the live data catalog to pull the real column names, types, and grain. It never invents a schema. If the logic references a column the catalog doesn't have, it emits [SCHEMA MISMATCH] and asks instead of guessing. If a table isn't registered at all, it emits [NOT SUBSCRIBED] and halts planning for that table. This grounding step is what makes a whole class of bugs visible at plan time — including the one that motivated the project (more on that below). The verified plan becomes the ground truth everything downstream validates against. The One Human Gate on the Frontnd (analyzed → user-confirmed) The execution plan is shown to a human before a single line of code is written. This is deliberate: a misread requirement is cheapest to fix here, before generation, testing, and review have compounded on top of it. The control plane simply stops and waits. No amount of agent confidence advances past this line — only a person does. Generation, Then Adversarial Review (generated → validated) A second agent — the Code Writer — takes the confirmed plan and generates the module: dataset configs, metric formulas, compute functions, the job orchestrator. Then the key move: a third agent — the Reviewer — is dispatched as a fresh, independent agent that did not write the code. It checks the generated output against the Analyzer's plan through a fixed multi-point checklist: Completeness (every planned step is present)Null safetyFilter correctnessJoin correctnessOutput schema — including a lossy-cast checkAnti-patternsCaching correctnessArchitecture complianceA behavioral check that actually runs the happy-path test The Reviewer denies by default. If the plan identified 10 steps and the code covers 8, it rejects — with specific, targeted feedback. If a null check present in the source is missing from the output, it rejects. This is the single most important design decision in the system, so it's worth stating as a principle: The agent that writes code never grades its own work. The agent that fixes a rejection never grades its own fix. Self-review by an LLM is theater — the model that just confidently produced wrong code is the same model asked to confidently bless it. Separation of writer and reviewer, enforced by the control plane spawning distinct agents, is what gives the check teeth. The Retry Loop With a Budget On rejection, the control plane increments a retry counter and bounces the module back to generated with a "pending fix" flag. The next dispatch is a targeted fix pass — minimal changes to only the cited issues, not a full rewrite — followed by a fresh review by (again) an independent reviewer. This loops until the Reviewer approves — in practice, 1–2 iterations — or the control plane escalates to a needs-human state after 3 attempts. It never loops forever, because "3 attempts then escalate" is a Python integer comparison, not a judgment call the model gets to make. Human at the Exit, Too (cr-ready → done) When review passes, a code review is created for engineers. They review pre-validated, reviewer-approved code — not raw first-pass output. Publishing is a human action. The agents never push to production. That boundary lives outside the agents by design. Why This Beats a Single Powerful Agent You might ask: with a strong enough model, why not just prompt one agent to "generate the module, validate it thoroughly, and retry if needed"? Because every guarantee in that sentence is soft. "Validate thoroughly" is aspirational. "Retry if needed" has no ceiling. "Don't skip steps" is a hope. The moment the task varies, the soft guarantees bend. Moving those guarantees into a state machine makes them hard: Concern Left to the agent In the control plane Gate ordering Model may reorder or skip Structurally impossible to skip Retry budget Model may loop or give up early Fixed count, then escalate Writer/reviewer separation Same context, self-blessing Distinct agents, fresh context Crash recovery Lost on session end State persisted to disk Production boundary Model could push No publish capability exists in the loop The agents still do what they're good at — reading messy specs, writing idiomatic code, inferring edge cases. They just don't get to decide whether they're allowed to proceed. A Concrete Payoff: The Lossy-Cast Regression The bug that started all of this: a decimal value silently cast to an integer, which truncated flag columns across dozens of tables. It wasn't caught by a compiler. It slipped through review. It surfaced only after more than a dozen production investigations. In this system, that exact regression is guarded in two independent places: The Reviewer's output-schema check flags lossy casts at review time, working from the real column types the Analyzer pulled from the catalog.The test generator carries it as a known-bug regression pattern, so a test for it is written automatically. The grounding step is what makes this possible — because the Analyzer resolved real types up front, a decimal → int mismatch is visible from the start rather than discovered in production. Results and Honest Caveats We validated the approach on a genuinely complex, production-grade module: multiple compute stages, ~10 surcharge components, ~120 output metrics across 8 config files. ~85% of the module was generated correctly out of the box.~15–25% still required manual review for business-specific edge cases.Engineering effort dropped substantially versus a full manual build. The honest caveat: this is not "fire the engineers." It's "stop making engineers do the boilerplate." The remaining edge-case work is exactly the work you want skilled humans on. And every gap we find gets fed back into the skill files as a reviewed change — so the knowledge plane improves module over module while the control plane stays fixed. Takeaways for Your Own Agentic Workflows If you're building LLM code generation (or any high-stakes agentic workflow), the transferable lessons are: Separate orchestration from cognition. Put sequencing, retries, and escalation in deterministic code. Let the model do the creative work only.Make gates unskippable, not just documented. A checklist in a prompt is a suggestion. A state machine is a contract.Never let an agent grade its own work. Spawn a fresh reviewer with no stake in the output, and make it deny by default.Bound your retries in code. "Try a few times then escalate" must be an integer comparison, not model discretion.Keep humans at the expensive-to-reverse boundaries — confirming intent up front, and publishing to production at the end.Ground the model in real state before it plans. Read the actual schema/environment; make the agent flag mismatches instead of inventing. The agent accelerates. The control plane keeps it honest. Neither is optional More
Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy

Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy

By Stelios Manioudakis DZone Core CORE
This part answers the practical question: given all of this, what do you actually test, where, and how? This part answers using an example that covers all three regimes. Fundamental tests for each regime are addressed. Tables summarizing more elaborate lists of testing activities are presented in the appendix. A Scenario Covering All Regimes A technician working in a basement with no coverage uses a tablet app to order a replacement part, building the order offline. Forty minutes later, coverage returns and the app syncs the order to the nearest of three regions, where the core checkout validates stock, charges the customer's account, and notifies the technician. Because the part is stocked by a wholesale distributor, an adapter writes the order into that night's batch file, and the distributor's confirmation comes back in a response file somewhere between 6 hours and 3 days later. The same order passes through the weak-time edge (regime 2), the partially synchronous core (regime 1), and the no-time batch integration (regime 3), in that order. For each stage, we list a sample of fundamental tests. The appendix holds the tables of techniques by level, with the remaining techniques for each level and an example test for each. All figures are illustrative. Stage 1: The Device and the Edge (Regime 2, Weak Notion of Time) The tablet's clock cannot be trusted. Delivery can be duplicated or reordered, and the delay is open-ended. Correctness has to come from logical ordering and idempotent replay. Property-based testing of merge and ordering logic. State the rules (merging two versions of an order is commutative, associative, and idempotent) and generate thousands of random edit histories with random delivery orders. A failure could arrive as a minimal counterexample, such as a part removed and re-added on two devices ending up as two lines in one replica and one in the other.Deliberately wrong clocks. Create edits stamped years ago or tomorrow, and run the real app with the device clock set two days back. Ordering must come from logical versions, so a tablet running two days fast cannot win every conflict.Idempotence under duplicates and crashes. Send the same submit request five times, concurrently and after a consumer restart, and also fail the system between the side effect and its deduplication record. Exactly one purchase order may result, and the assertion is on the resulting state, not on call counts.A simulated device. Model the tablet's queue, clock, and connection, then generate sequences: go offline, queue 10 actions, reconnect in a different order with 3 duplicates, crash the sync client midway. Compare the server state with a simple model. It finds bugs such as acknowledged actions that are never removed from the queue and are resent forever.Schema compatibility with old app versions. Tablets in the field replay messages written up to a year ago, so the newest consumer must still read them, and old consumers must tolerate added fields.Partition testing with a convergence check. Cut one region off for 2 hours and run another for an open-ended period, while both sides accept orders. Writes must be queued or explicitly rejected, never silently dropped, and replicas must converge after healing without a double order reaching the supplier.Offline, double-submit and multi-device tests. Go offline, build an order, reconnect and expect exactly one order; click submit twice; edit the same order on two devices and expect a visible conflict rather than a silent overwrite.Replication and reconciliation monitoring. Track replication lag, the conflict rate, and orders stuck in syncing, and check invariants hourly, such as no order submitted twice. Pre-release tests only sample this space; production checks cover it continuously. Stage 2: The Core Region (Regime 1, Partially Synchronous) Timeouts are meaningful here, so the work is calibrating them and keeping the system stable when load and degradation arrive together. Boundary value tests of timeouts and retries. With a fake clock, test a 400 ms retry budget at 399 ms (no retry), at 401 ms (exactly one retry) and after a third failure (an error, not a fourth attempt). Add a table of error level, temporality and attempt number so that an application-level failure, which cannot succeed, never retries.Mutation testing of that logic. Deliberately break the retry code (remove the cap on total retry time, flip a comparison) and run the suite. A surviving mutant marks a behavior nothing asserts, and a missing cap is exactly what produces retry storms.Scripted dependencies that are slow or failing. Make the card gateway answer in 300 ms normally, in 3 seconds for 5% of calls, and with a 503 twice for one order. Assert no second charge on a slow answer and that no order ends with zero or two charges. Slow and failed are different cases.Component tests against a real broker. Consume a message, kill the consumer before it commits its position, restart it, and assert one equivalent charge. A mock would only encode the team's assumption about redelivery.Consumer-driven contract tests. The payment service declares the StockReserved fields it relies on. The inventory build checks them, so a field renamed to tidy a schema fails the inventory build instead of the checkout.Load and degradation together. Apply five times normal load and, in the same run, 90 seconds of packet loss in one availability zone. Assert no retry storm, no cascade into the notification service, and full recovery afterwards. Neither the load alone nor the fault alone reveals the defect.Correlation and trace assertions. Place 1,000 orders carrying a correlation identifier. Each must end confirmed or cancelled with exactly one charge, and the trace must show no second charge attempt hidden behind a correct end state.Canary releases, synthetic orders and alert tests. Release changes to 5% of traffic against a baseline, place a synthetic order every minute, and test the alert rules themselves against synthetic data. The latency distribution drifts, so calibration must be re-validated continuously. Stage 3: The Distributor (Regime 3, No Notion of Time) No timeout can serve as a failure detector. We rest on the file contract and on reconciliation. Much of the testing becomes permanent operational activity. Boundary and malformed-input tests of the file contract. Generate files with 0, 1, the maximum and one more line items, zero and negative quantities, over-long codes and truncated content. The generator must refuse invalid input and the parser must reject a partial file instead of ingesting it. With no live handshake, the format is the entire contract.Fuzzing the response parser. The response comes from another organization, so feed it mutated and truncated variants. It may reject them but must never crash, hang or half-apply a file.Table-driven reconciliation tests. Sent 100 and acknowledged 98 reports 2 missing; an acknowledgment for an unknown order is reported; a duplicate counts once; shuffling the acknowledgments changes nothing.A simulated drop folder. Control arrival: the response never arrives, arrives twice, arrives half-uploaded, or arrives valid but with conflicting quantities. Seed 20 known discrepancies and assert that exactly those are reported, independent of when in its cycle the job ran.A round trip against the partner's sandbox over real elapsed time. Exchange files across at least 48 hours each release. Waiting is the point: it exposes a credential that expires on day 2 or a batch window that shifts after the partner's clock change.Pending states and usability tests. The technician should see that the order was sent and is awaiting confirmation. There is no confirmation after 36 hours and it has been escalated, not a blank. Ask users what they would do at 36 hours; if the answer is to send it again by hand, the design invites duplicates.Scheduled reconciliation, baseline monitoring and runbook drills. A daily job reports orders sent but not acknowledged past the 36-hour grace period (a business policy, not a technical threshold). Arrival times are compared with the last 90 days to distinguish a slow day from a broken integration, and a tabletop exercise rehearses a response that is 48 hours late. Across the Boundaries Every handoff between stages needs its own contract-style test: idempotent replay from device to region, an exactly-once effect on the file write from the broker to the adapter even if the adapter restarts, and reconciliation and deduplication when the response returns. A correlation identifier created on the tablet should appear in the file's line identifier and in the reconciliation report. One order can be followed through all three regimes. The terminal state, that the part has arrived, can only be verified by reconciliation, not by waiting for it. Wrapping Up The idea underlying everything in this article is that correctness, scalability, and reliability of a distributed system are emergent properties. They belong to the system as a whole and not to a single component. A payment service can pass every unit test in isolation and still double-charge once it sits behind an unreliable queue with a naive retry policy in front of it. Testing each component correctly is necessary. It is never sufficient. The failure taxonomy and the delivery and processing semantics covered here are the minimum vocabulary needed to evaluate what and how to test. Guessing semantics by looking at old incident reports is never sufficient. A comprehensive async test suite is not the one with the most tests. It is the one that can be traced, cell by cell, to an explicit map of components. The one that can be traced to a classification of how asynchronous each connection really is. It is the test suite behind deliberate decisions about which failure modes are in scope and which are explicitly, documentedly, not. Appendix A table of possible testing activities is presented at the unit level, the API level and at system level. Each activity or technique is categorized, explaining the test itself, what it verifies and the regimes that it can be used for. All tables are indicative. A.1 Unit Unit tests are the cheapest place to get timing and failure logic right, because a fake clock and fake I/O make asynchrony deterministic. techniquewhat it verifiesexample asynchronous testregime Specification-based design Equivalence partitioning and boundary value analysis Decision logic at the edges of its input and time ranges: timeout thresholds, retry limits, backoff caps, batch sizes, TTLs. Retry policy with a 200 ms timeout: assert behavior at 150, 199, 201 and 500 ms of simulated latency; test the retry limit at N-1, N and N+1; test the largest accepted message size. 1 Decision-table testing Combined conditions that select a recovery action. A table of error level x temporality x attempt number: a platform-level transient failure on attempt 1 retries at once; an application-level failure compensates; exhausted retries escalate. One test per row. 1 State-transition testing Workflow and handler state machines: legal and illegal transitions, including events that arrive twice or out of order. The order state machine receives PaymentCompleted before StockReserved, or the same event twice; assert the transition table and that no illegal state is reachable. 1, 2 Approval (snapshot) testing Stable shape of serialized messages, generated batch files and notification templates. Snapshot the OrderPlaced message and the outbound batch file; a diff flags an accidental field rename or reordering that would break a downstream consumer. 2, 3 Metamorphic testing Relations that must hold between outputs when no exact oracle exists. Reconciliation output is unchanged when the acknowledgment list is shuffled; processing a message log twice equals processing it once; an unrelated message does not change an order's outcome. 2, 3 Structure-based analysis Coverage analysis (statement, branch, condition) Whether failure-handling code is exercised at all: catch blocks, timeout branches, compensation paths. The coverage report shows the payment handler's refund-failure branch never runs; add a test that forces it. All Mutation testing Whether the tests would notice a bug in timing, retry and deduplication logic. Mutate >= to > in a timeout comparison, delete the dedupe check, or change the retry counter. Every surviving mutant points at a missing assertion. 1, 2 Static analysis and code review Async mistakes visible without running anything: missing timeouts, unawaited promises, blocking calls on an event loop, unbounded retries, swallowed exceptions, inconsistent lock ordering. A lint rule fails the build on a floating promise; the review checklist asks whether every outbound call has a timeout and a retry budget and every consumer is idempotent. All Data-race detection Races and atomicity violations on shared in-process state such as caches, in-memory dedupe sets and counters. Hammer the dedupe store from 64 threads with overlapping keys under a race detector: no race reports, no double insert. 1 Message and data semantics Idempotence and duplicate-delivery testing Applying the same message once, twice or many times yields an equivalent state. Call the handler with one message and one idempotency key 1, 2 and 5 times and compare the final state; make a dependency fail between the side effect and the key write. All Out-of-order delivery testing Consumer logic against every permutation of a short event sequence. Feed all 6 orderings of three events and assert the same final state or an explicit, correct rejection. 2, 3 Input-space exploration Property-based testing Invariants over many generated inputs and operation sequences. merge(a, b) equals merge(b, a); any permutation or duplication of operations converges to the same state; backoff is non-decreasing and capped. 2 Fuzzing Parsers and deserializers against malformed, truncated and adversarial input: message envelopes, EDI or CSV batch files, message payloads. Fuzz the batch-file parser for hours: no crash, no hang, no unbounded memory, and bad input yields a typed error instead of a half-parsed order. All Interface, integration and contract Test doubles and service virtualization Handler logic in isolation, with dependencies scripted to fail, stall or misbehave. Stub the payment gateway to time out twice, then succeed; assert two retries, correct backoff and one recorded charge. 1 Concurrency and timing Systematic concurrency testing Interleavings of async tasks explored deterministically instead of by luck. Explore every schedule of two tasks debiting one balance; a failing schedule is printed and can be replayed exactly. 1, 2 Virtual-time (fake clock) testing Time-dependent logic without real waiting: timeouts, heartbeats, backoff, TTLs, expiry. Advance a fake clock by 31 s and assert the circuit breaker opens; step the clock backward by 5 s and assert no negative durations or reordering. 1, 2 Condition-based waiting Async assertions that wait for an effect instead of sleeping for a fixed time. Poll until the handler's side effect appears, with a generous ceiling, and fail with a message that names the missing condition. 1, 2 Fault and resilience Fault injection (code level) Behavior when one specific statement fails, such as the gap between a side effect and the record that deduplicates it. Throw after the database write and before the idempotency-key commit; the retry must not duplicate the effect. All Non-functional Performance microbenchmarking Latency of hot paths whose cost feeds timeout calibration. Benchmark serialization, dedupe lookup and backoff computation; fail CI on a regression beyond a budget. 1 Security testing Message-level authentication and replay defenses. A tampered signature, an expired timestamp and a reused nonce are each rejected; an unauthorized sender is refused. 2, 3 Localization and internationalization testing Time zones, calendars and text in notifications and timestamps. An order placed at a DST change renders correctly; internal comparisons use UTC or monotonic time, never local time; every notification template has all placeholders in every locale. 2 A.2 API At the API level, asynchrony shows up as accepted-but-not-done responses, idempotency keys, webhooks and the agreements between teams. techniquewhat it verifiesexample asynchronous testregime Specification-based design Equivalence partitioning and boundary value analysis Limits at the API surface: payload size, rate limits, idempotency-key lifetime, deadline values. Request at the maximum body size and one byte over; call exactly at and just beyond the idempotency-key expiry; hit the rate limit at N and N+1 requests. 1 Functional API testing Endpoint behavior including async patterns: 202 Accepted with a status URL, polling, idempotency keys. POST /orders returns 202 and a status URL; poll until a terminal state; repeat the request with the same idempotency key and receive the same result. 1 Message and data semantics Idempotence and duplicate-delivery testing Idempotency keys: duplicate, concurrent, expired, and reused with a different body. Ten concurrent requests with one key produce one side effect; the same key with a different body is rejected. All Compatibility and versioning testing Old clients against new API versions during rolling deploys. Run the previous release's client test suite against the new server build. 1, 2 Consistency-model testing Read-your-writes, monotonic reads and bounded staleness across regions. Write through region A and immediately read through region B: either the new value or an explicit pending state, never a silent absence; measure the staleness window. 2 Input-space exploration Property-based testing Generated request sequences checked against API invariants. Requests are derived from the API specification and checked: no response may violate the schema or return a 5xx. 1, 2 Fuzzing Stateful sequences of calls that find crashes, 5xx errors and state bugs. A generator derives dependency-aware call sequences from the API specification (create order, pay, cancel, retry) and reports unexpected server errors. 1, 2 Interface, integration and contract Spec-driven API conformance testing Responses and events match the published API specification. Validate every response and every published event against its specification in CI; fail the build on an undeclared field or status code. All Asynchronous API lifecycle testing Eventual completion, polling behavior, webhook delivery, retries and signatures. A webhook receiver gets the same event twice and out of order; it verifies the signature and applies the event once. 2, 3 Negative and error-path testing Status codes, error bodies, rate limiting and partial failures. A 429 with Retry-After is honored; a 503 triggers a retry rather than a user-visible failure; a timeout returns a clear pending status. 1 Consumer-driven contract testing API expectations of each consuming client or service. Each mobile and web client publishes the response fields it relies on; the provider build fails if one disappears. 1, 2 Test doubles and service virtualization The API under test with its downstream services scripted. Slow the downstream inventory stub and assert the API returns 202 with a pending status instead of blocking. 1 Fault and resilience Fault injection (network) Deadline propagation and graceful degradation at the API boundary. A client deadline of 2 s must reach downstream calls and no work continues after cancellation; add latency to a dependency while calling the API. 1 Non-functional Load, stress and spike testing Throughput, latency distribution, saturation, retry storms and queue growth at the API. Ramp load and add a spike while a dependency slows down; watch p99, error rate and consumer lag, and confirm the system recovers. 1 Security testing Authentication, authorization, injection, replay, rate limiting and SSRF in webhooks. Replay a captured request after the signature window; probe object-level authorization on order IDs. 2, 3 A.6 System (End-to-End) System tests are the only level where load, partial failure and several components interact, so they carry the resilience and end-to-end techniques. techniquewhat it verifiesexample asynchronous testregime Specification-based design Scenario-based testing Business flows across all components, including honest pending states. Place an order, poll until confirmed, and assert exactly one email and one charge, using a correlation ID instead of a fixed wait. All Regression testing Every production incident becomes a permanent test at the lowest level that reproduces it. A duplicate charge found in production becomes an idempotence test; a lost response becomes a retry test. All Smoke testing After every deploy, a minimal path through each async channel works. Publish a test message through each topic and confirm consumption, the side effect and the acknowledgment. All Combinatorial (pairwise) testing Fault, location, timing and load combinations without running all of them. Generate pairwise experiments from {kill, pause, latency, loss} x {broker, consumer, database} x {idle, loaded}. 1, 2 Message and data semantics Consistency-model testing Recorded histories of concurrent operations checked against a consistency model. Record the operations of concurrent clients during partitions and check the history for linearizability or serializability violations. 2 Reconciliation and data-integrity testing Full round trip with a partner sandbox over real elapsed time. Exchange files with the partner sandbox across a realistic window, at least once per release, and reconcile every record. 3 Compatibility and versioning testing Mixed versions during rolling upgrades and migrations. Roll consumers one by one while producing; messages from version N are consumed by N+1 and the reverse, with no loss or duplicate effect. 1, 2 Concurrency and timing Deterministic simulation testing The whole system in one process with a simulated network, disk and clock, reproducible from a seed. A simulator drops, delays and reorders messages at random; a failing seed reproduces the exact failure every time. A heavy investment, mostly for new infrastructure. 1, 2 Fault and resilience Fault injection (network) Resilience under realistic load: retry storms, cascades, recovery. Sustained load while latency is injected for one availability zone; assert no retry storm, no cascade, and full recovery after the fault lifts. 1 Fault injection (process and resource) Crash, pause and restart of real components in a full environment. Kill the payment service between reserve and charge; pause the broker leader; verify the order still completes or compensates. 1 Network partition testing Multi-region divergence, split-brain and reconciliation after healing. Partition one region for 10 minutes while both sides accept writes; heal and assert convergence with no silent loss. 2 Byzantine fault injection Only where participants are not fully trusted: consensus layers, multi-party systems, adversarial input. A duplicated node (two instances sharing one identity) presents conflicting messages; forged events are published directly to the broker. 2 Recovery, failover and disaster-recovery testing Recovery time and data loss, restore from backup, region failover, replay from the log. Fail region A; measure the time until region B serves traffic and verify that no acknowledged order is lost. 2 Non-functional Load, stress and spike testing Sustained, peak and sudden load on the full pipeline. Replay a peak-hour message rate plus a 3x spike and watch end-to-end latency to confirmation. 1 Soak (endurance) testing Slow leaks and drift over days: memory, connections, queue growth, clock drift, certificate expiry. Run 72 hours of steady load while tracking memory, consumer lag and open connections. 1, 3 Scalability and capacity testing How throughput scales with consumers and partitions, and where it stops. Double the consumer count and measure throughput until the partition count caps it. 1 Observability testing Assert on the actual causal path through the services, not only the end state. A test asserts that spans for gateway, inventory, payment and notification exist in causal order and that no second charge span appears. All Configuration testing Timeouts, retry budgets, flags and limits are what you calibrated, in every environment. A policy check fails if a production timeout differs from the calibrated value or a retry budget is unbounded. 1 Security testing Threat scenarios across channels: forged events, replay, poison-message denial of service. Publish a forged OrderPlaced directly to the broker without credentials; expect rejection and an alert. All More
Relate, Jev, and MCP: A Judgment Ledger for Agent Decisions
Relate, Jev, and MCP: A Judgment Ledger for Agent Decisions
By Akmal Chaudhri DZone Core CORE
Seven Failure Modes Every HTTP Client Should Handle: Lessons From Fixing 31 Bugs
Seven Failure Modes Every HTTP Client Should Handle: Lessons From Fixing 31 Bugs
By Mohammad Garmabi
Integrating Jev via REST With Java and Spring RestClient
Integrating Jev via REST With Java and Spring RestClient
By Horatiu Dan DZone Core CORE
Terry: A Live File Tree and Review Gate for Claude Code
Terry: A Live File Tree and Review Gate for Claude Code
By Eric D. Schabell DZone Core CORE

More Articles

AI Governance by Design: From Model Risk to Production Accountability
AI Governance by Design: From Model Risk to Production Accountability

The AI Governance Dilemma Artificial intelligence technologies are quickly disrupting enterprise engineering, software engineering, finance, and operations decisions. Businesses are implementing machine learning algorithms, generative AI helpers, and increasing autonomy in their processes in order to increase productivity, innovate faster, and improve customer experience. Nevertheless, with the rapid growth of AI applications comes an important question: Who is responsible for a wrong, biased, or even potentially dangerous decision made by AI? Traditionally, software engineering focuses on functionality, performance, security, and reliability of software applications. In AI implementation, these criteria are not enough because of the probabilistic nature of its output, unpredictability, model drift, automation bias, and changing regulatory requirements. It means that a new mindset is needed; AI governance cannot be seen as a compliance activity conducted before production implementation anymore. AI governance should become an engineering discipline itself. The fundamental question is no longer simply whether organizations can implement AI, but whether they can govern it responsibly. AI governance establishes the policies, principles, decision rights, responsibilities, processes, and oversight mechanisms necessary to ensure AI systems are developed, deployed, monitored, and retired responsibly. Governance is not just about compliance. It is the ability of the organization to make informed decisions, manage risk, and be accountable and transparent, all while retaining control over the AI throughout its entire lifecycle. 1. AI Governance Principles vs. Frameworks It is important to recognize the difference between the two concepts in order to set up good artificial intelligence (AI) practices. AI governance principles set objectives for responsible AI. Some examples include fairness, accountability, transparency, privacy, safety, reliability, and human supervision. Frameworks of AI governance, on the other hand, provide processes and procedures that turn the principles into practice, control, responsibility, and results. Fairness is a principle; assessing bias, setting standards, recording outcomes, and measuring performance form a framework for implementing fairness. Three of the commonly known governance references are: NIST AI RMF: This framework organizes the AI risk management process into four interrelated functions: GOVERN, MAP, MEASURE, and MANAGE.ISO/IEC 42001: This framework outlines the requirements to implement and continuously improve the AI management system in the organization.OECD AI Principles: The OECD AI Principles provide guidance based on values that focus on trustworthy AI, human rights, transparency, robustness, and accountability. Principles provide strategic guidance, and frameworks guide implementation in practice. It must be noted that both principles and frameworks do not override any applicable legislation. 2. AI Governance Across the Six-Stage Lifecycle AI governance should begin before development and continue throughout the process until the system is safely decommissioned. Stage 1: Intake and Classification Determine whether AI is appropriate for the business problem, identify all stakeholders, outline possible risks, and determine the required approval path. Companies should outline intended use, business value, stakeholders involved, business impact, autonomy, and possible negative effects. For example, an internal productivity assistant will have different protections than an AI model that makes credit approval decisions. Governance checkpoint: Use Case Approval, Owner Identified, Risk Classification, and Assessment Completed. Stage 2: Data and Model Selection Review the quality, origin, representativeness, rights, privacy concerns, and suitability of the model. Poor-quality data or data that lacks representativeness will give incorrect predictions or outcomes even if the architecture of the model is sophisticated. Businesses must also assess model vendors, contractual issues, data governance issues, and third-party issues. Governance checkpoint: Data governance assessment, model suitability evaluation, and privacy and security assessment. Stage 3: Development and Validation Test AI systems based on pre-existing acceptance criteria, which include criteria such as accuracy, robustness, fairness, explainability, security, and performance. For generative AI systems, consider tests related to hallucination, prompt injection, unsuitable disclosures, and unreliable recommendations. Tests need to relate to actual business processes rather than simply benchmarks. Governance checkpoint: Evidence of testing compliance, acceptance criteria, limitations, and remediation actions for identified risks. Stage 4: Deployment Confirm required approvals, human oversight, operational readiness, monitoring capabilities, rollback procedures, and incident response arrangements. Production deployment should occur only when relevant stakeholders understand system limitations and have accepted residual risks within authorized boundaries. Governance checkpoint: Deployment authorization, readiness assessment, assigned operational ownership, and documented contingency procedures. Stage 5: Monitoring and Change Management Determine whether the AI system is continuing to perform acceptably within performance and risk criteria. Changes to data, prompts, models, integrations, autonomy, and purpose can bring about risks that were not considered in previous authorizations. The monitoring process will identify deteriorating performance, changes in the model, vulnerabilities, and unforeseen impacts on the business. Governance checkpoint: Information obtained from monitoring and changes. Stage 6: Retirement Decommission systems that have been rendered obsolete, unreliable, economically non-viable, or inappropriate for organizational or regulatory purposes. The retirement phase includes aspects such as data retention issues, access removal, system dependency management, and preparing the necessary documentation. Governance checkpoint: Decommissioning authorization confirmation, access removal, data disposal, and audit evidence. It should be noted that the various stages are cyclical in nature, as changes or events will require one to go back to the previous steps of assessment and validation. 3. Making AI Accountability Measurable Governance becomes operationally meaningful when organizations translate responsibilities into measurable controls. An enterprise AI governance scorecard should monitor: accountability metricmeasurement objective AI ownership coverage Percentage of AI systems with assigned accountable owners Risk assessment completion Percentage with current documented assessments Model reliability Performance against approved accuracy and quality thresholds Human oversight adherence Required human reviews completed Control effectiveness Required controls operating as intended Incident remediation Corrective actions completed within approved deadlines Change compliance Material AI changes reassessed before implementation It is important for each metric to have a responsible owner, frequency of reports, escalation point, and evidence to back it up. An example would be when a knowledge assistant built on generative AI achieves 97% accuracy in its response rate. Nonetheless, if the remaining 3% of errors occur due to mistakes in providing instructions for financial tasks, it would be insufficient for determining acceptance based on average accuracy alone. Accountability must consider the severity and consequences of failures, not simply average model performance. 4. Essential AI Terminology for Governance Professionals Technology leaders should understand common AI concepts because each introduces specific governance implications. ai terminologymeaning and governance relevance Hallucination Fabricated or unsupported AI output; requires grounding and factual validation Overfitting Poor generalization despite strong training performance; requires independent testing Underfitting Failure to learn meaningful relationships; requires model evaluation Data drift Changes in input data distributions; requires monitoring Concept drift Changes in input-output relationships; requires reassessment Human-in-the-loop (HITL) Human participation at defined decision points Human-on-the-loop (HOTL) Human supervision of autonomous operations with intervention capability Human-out-of-the-loop Automated operation without direct human intervention during normal execution Explainability Ability to provide understandable explanations of AI outputs Algorithmic bias Systematic errors or disparities requiring fairness evaluation Retrieval-Augmented Generation (RAG) Generation informed by retrieved knowledge; requires source and retrieval quality controls Prompt injection Malicious instructions attempting to manipulate model behavior AI guardrails Safeguards restricting unauthorized or unsafe behavior Agentic AI Goal-directed systems capable of executing actions; requires autonomy and permission controls Model drift Changes in model behavior or performance requiring ongoing evaluation These concepts connect technical model behavior with organizational risk, accountability, and governance decisions. 5. Applying Governance to Enterprise Generative AI Imagine a contact center at a bank using an AI assistant responsible for fetching approved procedures and suggesting customer service actions. Although this AI application has great potential for increasing efficiency, it might also generate hallucinations that would give faulty suggestions, be based on out-of-date information, making it unreliable, and foster excessive confidence in its suggestions among employees. Good governance requires validated sources of information, extensive accuracy testing, proper safeguarding of confidential information, significant human intervention, employee feedback, and continued monitoring of production. In addition, the company should establish responsibilities for system suspension, investigations, approvals, and release of updates. This results in an accountable audit trail: AI behavior → Risk identification → Governance control → Performance metric → Corrective action Conclusion: Governance as Continuous Assurance It is important not to view AI governance as simply a one-off exercise, a list of requirements, or a job for IT departments alone. Instead, AI governance must be viewed as a complex process that combines organizational capabilities in terms of both business strategy and technical implementation. Governance is all about finding the right balance between innovation and responsible risk management so that companies can still explain, oversee, question, and correct AI-driven results. Ultimately, AI governance is not about making sure that an AI system has been deployed or approved, but that the company can keep proving that it is trustworthy and fit for its purpose.

By Pabitra Saikia DZone Core CORE
The Query Takes 20 ms. Why Does the API Take Two Seconds?
The Query Takes 20 ms. Why Does the API Take Two Seconds?

A developer notices that an API endpoint takes almost two seconds to respond. The first suspect is the database, so the team checks the query logs, reviews the execution plan, and looks for anything that might explain the delay. The query finishes in 20 milliseconds. Database CPU usage is normal, and nothing in the monitoring dashboard suggests a serious problem. Yet users are still waiting two seconds for a response. It's easy for investigations like this to become focused on the database, especially when an endpoint spends much of its time retrieving information. But a fast query tells us very little about what happens before the database receives it or after the results return. To find the delay, we need to follow the request through the application and understand where those missing milliseconds are going. The Missing 1,980 Milliseconds Figure 1. An API request passes through multiple stages, adding delays beyond database query execution. Consider an API endpoint that retrieves a customer's recent orders. The database executes the main query in 20ms, but the entire request takes 2,000ms. That leaves 1,980ms to account for. The first thing to check is where each measurement begins and ends. Database execution time usually describes the work performed by the database engine. The application has other responsibilities, including receiving the request, obtaining a database connection, processing the returned data, and preparing a response. Depending on how monitoring is configured, some of these operations may not appear in the database logs at all. This matters when engineers start optimizing the SQL statement. Suppose they reduce execution time from 20ms to 10ms. They've improved query performance by 50%, but the overall response time would drop by only 10ms if everything else stayed the same. The user may barely notice the difference. Before changing anything, I'd want to know how much time the request spends at each stage. Even a basic breakdown can prevent hours of work on the wrong problem. Where Requests Wait Before Reaching the Database One place worth investigating is the database connection pool. Most applications reuse a limited number of database connections rather than opening a new connection for every request. This reduces connection overhead, but it also creates a shared resource that requests may have to wait for. Imagine an application with ten available connections. All ten are occupied when another request arrives. That request must wait until a connection becomes available. Once it gets one, the database might complete the query in 20ms, even though the application spent several hundred milliseconds waiting beforehand. This behavior is documented in HikariCP's configuration guide. When the pool reaches its configured maximum, and no idle connections remain, a request for a connection can block until one becomes available or the connection timeout is reached. A common reaction is to increase the pool size. Sometimes that helps, but I'd first investigate why connections are staying occupied. For example, an application might hold a database connection while waiting for an external service. Under heavy traffic, several slow operations can leave other requests waiting unnecessarily. Worker threads can cause similar problems: if all available workers are busy, incoming requests may spend time in a queue before processing begins. Connection acquisition time, pool utilization, and request queue length can help distinguish these problems from slow database execution. When Fast Queries Add Up to a Slow Request Another possibility is that the endpoint executes far more queries than expected. Imagine an API that retrieves 50 customer orders. The initial query finishes in 20ms. The application then retrieves the items associated with each order through separate database queries. This is commonly called the N+1 query problem. If those 50 additional queries each take 15ms and execute sequentially, they add 750ms to the request. Every query may appear fast in isolation, but the total cost becomes significant when the application makes so many database round trips. The problem becomes easier to identify when engineers examine the number of queries executed during a single request, rather than looking only at individual query durations. The application may also spend considerable time preparing the response. Converting database records into JSON requires processing, and the cost can grow when the response contains large amounts of data. Then there are external services. An order-history endpoint might contact a delivery provider to retrieve shipment information. If that service takes 500ms to respond and the application waits for it synchronously, that delay becomes part of the user's request time. By this point, it's easy to see how an API can take two seconds to respond without any individual SQL statement being particularly slow. Finding the Actual Bottleneck Figure 2. Distributed tracing reveals where time is spent across database operations, application processing, and external services. The challenge is collecting enough information to identify where the time is going. This is where distributed tracing becomes useful. Rather than showing only the total duration of a request, tracing records its journey through instrumented components and operations. OpenTelemetry provides a framework for collecting traces, metrics, and logs. With suitable instrumentation, engineers can examine database calls, outgoing HTTP requests, and application operations in the context of the same request. Consider a hypothetical trace for our two-second endpoint: request stageelapsed time Waiting for a database connection 400ms Database operations, including repeated queries 800ms Waiting for an external service 500ms Other application processing and overhead 300ms Total response time 2,000ms These figures are illustrative. They represent separate, non-overlapping portions of the request's elapsed time, not measurements from a real application. Actual traces may contain nested or overlapping spans, so their durations cannot always be added together. The example nevertheless shows why the 20ms query isn't necessarily the right place to start optimizing. The investigation needs to account for the entire request, including time spent waiting for shared resources and external dependencies. I'd also compare requests made during quiet periods with those made during peak traffic. If connection wait times rise sharply under load, that suggests a different problem from an endpoint that remains slow even when traffic is low. Average response times can hide what some users experience, too. Looking at the 95th and 99th percentile latency helps reveal requests that take unusually long to complete, even when most requests are fast. The aim is to understand the path taken by slow requests instead of relying on a dashboard that summarizes everything into one number. Fixing the Delay Without Guesswork Once the team knows where the time is being spent, the next decision becomes easier. If requests are waiting too long for database connections, I'd examine how connections are used and released. Long-running transactions, unnecessary connection holding, and excessive concurrency deserve attention before pool settings are changed. If repeated queries account for most of the delay, fetching related records together may reduce the number of database round trips. The team should then measure the result to make sure the change improves the complete request rather than just an individual query. Where external API calls are responsible, the team can review timeouts, cache suitable information, or run independent operations concurrently. Each option has trade-offs. Caching introduces freshness concerns, while increasing concurrency may improve an individual request but put additional pressure on the database or another shared service. The same principle applies to response serialization and application processing. If profiling shows that preparing a large response consumes significant time, reducing unnecessary fields or processing fewer records may help more than changing the database query. Whatever the suspected cause, I'd avoid judging a change solely by how it performs in a quick local test. Run the same representative workload before and after the improvement. Compare overall API response time, including slower requests, and check whether error rates or resource usage have changed. Where possible, keep the workload and test conditions consistent so the results are meaningful. A useful performance fix should produce a measurable improvement under conditions that resemble actual usage. Conclusion When a database query takes 20ms, and the API takes two seconds, the investigation shouldn't end with the query plan. There's still a considerable amount of application activity to examine. Requests may wait for connections, trigger dozens of additional queries, spend time processing large responses, or depend on external services that respond slowly. For me, the most useful starting point is understanding the complete request before deciding what needs optimization. It helps engineers avoid spending time improving a component that was already performing well. A fast database query is encouraging. The real improvement comes when the application delivers that speed to the user.

By Samuel Ogbonna
Migrating My Java Codebase to EE10
Migrating My Java Codebase to EE10

In the past few months, I have been struggling to update my JAVA codebase to the newest libraries and standards. Now that I am seeing some light at the end of the tunnel, I thought I'd share my experience, because I'm sure I am not the only one dealing with incompatible, outdated libraries and multiple developments happening at the same time. This first contribution will be part of an irregular series that I aim to share when I've made progress I think may help the community. The Problem Let's start by setting the scene. I have been developing Eclipse RAP/RCP applications since the early 2000s in a pure OSGi setting. My Java codebase has therefore evolved with changing architectural views and developments, and has tended to rely on a few libraries that together allowed me to develop enterprise-based solutions. As of 2022, this was based on: Eclipse RAP 3.15 for UI widgets, running on a Jetty ServerJavax.servlet 2.x for static resources and supporting web componentsorg.eclipse.http.registry for registration of Web resourcesJavax.ws.rs and Jersey 2.x for RESTful microservicesEclipseLink 2.x for persistenceGemini JPA and DBAccess for database connectivity (using MySQL connectors)Eclipse Virgo as the server-side OSGI containerEclipse Tycho (2.x) target definitions as a mix of Maven dependencies and JAR files stored locally on my computer My bundles support JAVA 8 and upward Because of some personal circumstances, this codebase was dormant since the end of COVID in 2022, so last year I decided to embark on a mission to get my codebase updated to the newest standards: Eclipse RAP 4.6 for UI widgetsJakarta.servlet 6.x for static resources and supporting web componentsJakarta.annotations (and apache.felix.scr ) for Component HTTP resource registration Jakarta.ws.rs and Jersey 5.x for RESTful microservicesEclipseLink 5.x for persistenceReplace Gemini JPA and DBAccess, because they are no longer actively maintained Apache Karaf as the server-side OSGI container, for the same reasons as above Eclipse Tycho (5.x) target definitions purely as Maven dependencies My original plan to go cold-turkey blew up in my face because, at every level, fundamental choices had been made in the Java architecture and, as noted above, some of the libraries I depended on were no longer maintained. In the end, I decided to first take an intermediate step and see if I could get my current setup to the most recent libraries. This would mean the following changes to my original setup: Eclipse RAP 3.29 for UI widgetsJavax.servlet 4.x for static resources and supporting web componentsorg.osgi.service.http.whiteboard for HTTP resource registration Replace Gemini JPA and DBAccess, because they are no longer actively maintainedEclipse Tycho (5.x) target definitions purely as Maven dependencies Even this more modest goal proved to be challenging in itself. One of the first lessons I learned was that, to make this migration work, I needed to start thinking in terms of Enterprise Edition Versions, or Java EE x. I had never really let it sink in that my current setup basically used the Java EE 8 architecture and that the different libraries tend to work well together for that reason. The developers of Eclipse RAP also adopted this approach over the years, so RAP 3.x was based on Java EE 8, while RAP 4.x was already preparing for Java EE 11. This means my migration strategy had to follow the RAP codebase as closely as possible. This approach is reflected in my target definition: XML <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?pde version="3.8"?> <target name="commons-jpa.target" sequenceNumber="254"> <locations> <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit"> <repository location="https://download.eclipse.org/rt/rap/3.29"/> <unit id="org.eclipse.rap.equinox.target.feature.feature.group" version="3.29.0.20240605-1200"/> </location> <location includeDependencyDepth="none" includeDependencyScopes="compile" includeSource="true" missingManifest="generate" type="Maven"> <dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> <type>jar</type> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.14.0</version> <type>jar</type> </dependency> <dependency> <groupId>com.sun.activation</groupId> <artifactId>javax.activation</artifactId> <version>1.2.0</version> <type>jar</type> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> <type>jar</type> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.22.0</version> <type>jar</type> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.4.0</version> <type>jar</type> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> <type>jar</type> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> <type>jar</type> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> <type>jar</type> </dependency> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.1.1</version> <type>jar</type> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.4.0-b180830.0359</version> <type>jar</type> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.26.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.26.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.26.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j2-impl</artifactId> <version>2.24.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j2-impl</artifactId> <version>2.24.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.2.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.antlr</artifactId> <version>2.7.16</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.asm</artifactId> <version>9.9.0</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.core</artifactId> <version>2.7.16</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa.jpql</artifactId> <version>2.7.16</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> <version>2.7.16</version> <type>jar</type> </dependency> <dependency> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.equinox.security</artifactId> <version>1.4.700</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.hk2.external</groupId> <artifactId>aopalliance-repackaged</artifactId> <version>2.6.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.hk2</groupId> <artifactId>hk2-api</artifactId> <version>2.6.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.hk2</groupId> <artifactId>hk2-locator</artifactId> <version>2.6.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.hk2</groupId> <artifactId>hk2-utils</artifactId> <version>2.6.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.hk2</groupId> <artifactId>osgi-resource-locator</artifactId> <version>1.0.4</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet-core</artifactId> <version>2.48</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.48</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-common</artifactId> <version>2.48</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-server</artifactId> <version>2.48</version> <type>jar</type> </dependency> <dependency> <groupId>org.glassfish.jersey.inject</groupId> <artifactId>jersey-hk2</artifactId> <version>2.48</version> <type>jar</type> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.33.0-GA</version> <type>jar</type> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-commons</artifactId> <version>6.0.3</version> <type>jar</type> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-engine</artifactId> <version>6.0.3</version> <type>jar</type> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>6.0.3</version> <type>jar</type> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>6.0.3</version> <type>jar</type> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>3.5.10</version> <type>jar</type> </dependency> <dependency> <groupId>org.opentest4j</groupId> <artifactId>opentest4j</artifactId> <version>1.3.0</version> <type>jar</type> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.namespace.extender</artifactId> <version>1.0.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.component.annotations</artifactId> <version>1.5.1</version> <type>jar</type> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.jdbc</artifactId> <version>1.1.0</version> <type>jar</type> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.service.jndi</artifactId> <version>1.0.0</version> <type>jar</type> </dependency> </dependencies> </location> </locations> <includeBundles> <plugin id="com.google.gson"/> <plugin id="com.google.gson.source"/> <plugin id="com.ibm.icu"/> <plugin id="com.ibm.icu.source"/> <plugin id="org.apache.aries.spifly.dynamic.bundle"/> <plugin id="org.apache.commons.commons-codec"/> <plugin id="org.apache.commons.commons-codec.source"/> <plugin id="org.apache.commons.commons-io"/> <plugin id="org.apache.felix.gogo.command"/> <plugin id="org.apache.felix.gogo.command.source"/> <plugin id="org.apache.felix.gogo.runtime"/> <plugin id="org.apache.felix.gogo.runtime.source"/> <plugin id="org.apache.felix.gogo.shell"/> <plugin id="org.apache.felix.gogo.shell.source"/> <plugin id="org.apache.felix.scr"/> <plugin id="org.apache.felix.scr.source"/> <plugin id="org.eclipse.core.commands"/> <plugin id="org.eclipse.core.commands.source"/> <plugin id="org.eclipse.core.contenttype"/> <plugin id="org.eclipse.core.contenttype.source"/> <plugin id="org.eclipse.core.databinding"/> <plugin id="org.eclipse.core.databinding.beans"/> <plugin id="org.eclipse.core.databinding.beans.source"/> <plugin id="org.eclipse.core.databinding.observable"/> <plugin id="org.eclipse.core.databinding.observable.source"/> <plugin id="org.eclipse.core.databinding.property"/> <plugin id="org.eclipse.core.databinding.property.source"/> <plugin id="org.eclipse.core.databinding.source"/> <plugin id="org.eclipse.core.expressions"/> <plugin id="org.eclipse.core.expressions.source"/> <plugin id="org.eclipse.core.jobs"/> <plugin id="org.eclipse.core.jobs.source"/> <plugin id="org.eclipse.core.runtime"/> <plugin id="org.eclipse.core.runtime.source"/> <plugin id="org.eclipse.equinox.app"/> <plugin id="org.eclipse.equinox.app.source"/> <plugin id="org.eclipse.equinox.cm"/> <plugin id="org.eclipse.equinox.cm.source"/> <plugin id="org.eclipse.equinox.common"/> <plugin id="org.eclipse.equinox.common.source"/> <plugin id="org.eclipse.equinox.console"/> <plugin id="org.eclipse.equinox.console.source"/> <plugin id="org.eclipse.equinox.event"/> <plugin id="org.eclipse.equinox.event.source"/> <plugin id="org.eclipse.equinox.preferences"/> <plugin id="org.eclipse.equinox.preferences.source"/> <plugin id="org.eclipse.equinox.registry"/> <plugin id="org.eclipse.equinox.registry.source"/> <plugin id="org.eclipse.equinox.security"/> <plugin id="org.eclipse.equinox.security.source"/> <plugin id="org.eclipse.help"/> <plugin id="org.eclipse.help.source"/> <plugin id="org.eclipse.jdt.junit.runtime"/> <plugin id="org.eclipse.jdt.junit.runtime.source"/> <plugin id="org.eclipse.jetty.http"/> <plugin id="org.eclipse.jetty.http.source"/> <plugin id="org.eclipse.jetty.io"/> <plugin id="org.eclipse.jetty.io.source"/> <plugin id="org.eclipse.jetty.logging"/> <plugin id="org.eclipse.jetty.security"/> <plugin id="org.eclipse.jetty.security.source"/> <plugin id="org.eclipse.jetty.server"/> <plugin id="org.eclipse.jetty.server.source"/> <plugin id="org.eclipse.jetty.session"/> <plugin id="org.eclipse.jetty.util"/> <plugin id="org.eclipse.jetty.util.ajax"/> <plugin id="org.eclipse.jetty.util.ajax.source"/> <plugin id="org.eclipse.jetty.util.source"/> <plugin id="org.eclipse.osgi.util"/> <plugin id="org.eclipse.rap.filedialog"/> <plugin id="org.eclipse.rap.filedialog.source"/> <plugin id="org.eclipse.rap.fileupload"/> <plugin id="org.eclipse.rap.fileupload.source"/> <plugin id="org.eclipse.rap.jface"/> <plugin id="org.eclipse.rap.jface.databinding"/> <plugin id="org.eclipse.rap.jface.databinding.source"/> <plugin id="org.eclipse.rap.jface.source"/> <plugin id="org.eclipse.rap.nebula.jface.gridviewer"/> <plugin id="org.eclipse.rap.nebula.jface.gridviewer.source"/> <plugin id="org.eclipse.rap.nebula.widgets.grid"/> <plugin id="org.eclipse.rap.nebula.widgets.grid.source"/> <plugin id="org.eclipse.rap.nebula.widgets.richtext"/> <plugin id="org.eclipse.rap.nebula.widgets.richtext.source"/> <plugin id="org.eclipse.rap.rwt"/> <plugin id="org.eclipse.rap.rwt.osgi"/> <plugin id="org.eclipse.rap.rwt.osgi.source"/> <plugin id="org.eclipse.rap.rwt.source"/> <plugin id="org.eclipse.rap.ui"/> <plugin id="org.eclipse.rap.ui.cheatsheets"/> <plugin id="org.eclipse.rap.ui.cheatsheets.source"/> <plugin id="org.eclipse.rap.ui.forms"/> <plugin id="org.eclipse.rap.ui.forms.source"/> <plugin id="org.eclipse.rap.ui.source"/> <plugin id="org.eclipse.rap.ui.views"/> <plugin id="org.eclipse.rap.ui.views.source"/> <plugin id="org.eclipse.rap.ui.workbench"/> <plugin id="org.eclipse.rap.ui.workbench.source"/> <plugin id="org.hamcrest"/> <plugin id="org.hamcrest.core"/> <plugin id="org.hamcrest.core.source"/> <plugin id="org.junit"/> <plugin id="org.junit.source"/> <plugin id="org.objectweb.asm"/> <plugin id="org.objectweb.asm.commons"/> <plugin id="org.objectweb.asm.tree"/> <plugin id="org.objectweb.asm.tree.analysis"/> <plugin id="org.objectweb.asm.util"/> <plugin id="org.osgi.service.cm"/> <plugin id="org.osgi.service.cm.source"/> <plugin id="org.osgi.service.component"/> <plugin id="org.osgi.service.component.annotations"/> <plugin id="org.osgi.service.component.annotations.source"/> <plugin id="org.osgi.service.component.source"/> <plugin id="org.osgi.service.device"/> <plugin id="org.osgi.service.device.source"/> <plugin id="org.osgi.service.event"/> <plugin id="org.osgi.service.event.source"/> <plugin id="org.osgi.service.metatype"/> <plugin id="org.osgi.service.metatype.source"/> <plugin id="org.osgi.service.prefs"/> <plugin id="org.osgi.service.prefs.source"/> <plugin id="org.osgi.service.provisioning"/> <plugin id="org.osgi.service.provisioning.source"/> <plugin id="org.osgi.service.upnp"/> <plugin id="org.osgi.service.upnp.source"/> <plugin id="org.osgi.service.useradmin"/> <plugin id="org.osgi.service.useradmin.source"/> <plugin id="org.osgi.service.wireadmin"/> <plugin id="org.osgi.service.wireadmin.source"/> <plugin id="org.osgi.util.function"/> <plugin id="org.osgi.util.function.source"/> <plugin id="org.osgi.util.measurement"/> <plugin id="org.osgi.util.measurement.source"/> <plugin id="org.osgi.util.position"/> <plugin id="org.osgi.util.position.source"/> <plugin id="org.osgi.util.promise"/> <plugin id="org.osgi.util.promise.source"/> <plugin id="org.osgi.util.xml"/> <plugin id="org.osgi.util.xml.source"/> <plugin id="slf4j.api"/> <plugin id="org.osgi.service.jdbc"/> <plugin id="org.osgi.service.jdbc.source"/> <plugin id="org.osgi.service.jndi"/> <plugin id="org.osgi.service.jndi.source"/> <plugin id="org.eclipse.persistence.jpa"/> <plugin id="org.eclipse.persistence.jpa.source"/> <plugin id="org.apache.commons.commons-logging"/> <plugin id="org.apache.commons.commons-logging.source"/> <plugin id="org.glassfish.jersey.core.jersey-client.source"/> <plugin id="org.glassfish.jersey.core.jersey-client"/> <plugin id="org.glassfish.jersey.core.jersey-common.source"/> <plugin id="org.glassfish.jersey.core.jersey-common"/> <plugin id="org.glassfish.jersey.core.jersey-server.source"/> <plugin id="org.glassfish.jersey.core.jersey-server"/> <plugin id="org.glassfish.jersey.containers.jersey-container-servlet-core"/> <plugin id="org.glassfish.jersey.containers.jersey-container-servlet-core.source"/> <plugin id="org.eclipse.persistence.antlr.source"/> <plugin id="org.eclipse.persistence.antlr"/> <plugin id="org.eclipse.persistence.asm.source"/> <plugin id="org.eclipse.persistence.asm"/> <plugin id="org.eclipse.persistence.core.source"/> <plugin id="org.eclipse.persistence.core"/> <plugin id="org.opentest4j.source"/> <plugin id="org.opentest4j"/> <plugin id="org.osgi.namespace.extender.source"/> <plugin id="org.osgi.namespace.extender"/> <plugin id="org.osgi.service.coordinator"/> <plugin id="wrapped.junit.junit.source"/> <plugin id="wrapped.junit.junit"/> <plugin id="org.glassfish.hk2.osgi-resource-locator"/> <plugin id="org.glassfish.hk2.osgi-resource-locator.source"/> <plugin id="org.glassfish.jersey.inject.jersey-hk2"/> <plugin id="org.glassfish.jersey.inject.jersey-hk2.source"/> <plugin id="org.glassfish.hk2.api.source"/> <plugin id="org.glassfish.hk2.api"/> <plugin id="org.glassfish.hk2.utils.source"/> <plugin id="org.glassfish.hk2.utils"/> <plugin id="org.glassfish.hk2.external.aopalliance-repackaged"/> <plugin id="org.glassfish.hk2.external.aopalliance-repackaged.source"/> <plugin id="wrapped.aopalliance.aopalliance.source"/> <plugin id="wrapped.aopalliance.aopalliance"/> <plugin id="javassist"/> <plugin id="javassist.source"/> <plugin id="org.eclipse.osgi"/> <plugin id="org.eclipse.osgi.source"/> <plugin id="com.sun.activation.javax.activation"/> <plugin id="com.sun.activation.javax.activation.source"/> <plugin id="javax.validation.api"/> <plugin id="javax.validation.api.source"/> <plugin id="wrapped.javax.transaction.jta"/> <plugin id="wrapped.javax.transaction.jta.source"/> <plugin id="javax.ws.rs-api"/> <plugin id="javax.ws.rs-api.source"/> <plugin id="wrapped.javax.inject.javax.inject.source"/> <plugin id="wrapped.javax.inject.javax.inject"/> <plugin id="javax.annotation-api.source"/> <plugin id="javax.annotation-api"/> <plugin id="org.glassfish.hk2.locator.source"/> <plugin id="org.glassfish.hk2.locator"/> <plugin id="com.sun.mail.javax.mail.source"/> <plugin id="com.sun.mail.javax.mail"/> <plugin id="jaxb-api.source"/> <plugin id="jaxb-api"/> <plugin id="javax.persistence"/> <plugin id="javax.persistence.source"/> <plugin id="junit-platform-commons"/> <plugin id="junit-platform-commons.source"/> <plugin id="junit-platform-engine"/> <plugin id="junit-platform-engine.source"/> <plugin id="junit-platform-launcher"/> <plugin id="junit-platform-launcher.source"/> <plugin id="junit-vintage-engine"/> <plugin id="junit-vintage-engine.source"/> <plugin id="org.apache.logging.log4j.api.source"/> <plugin id="org.apache.logging.log4j.api"/> <plugin id="org.apache.logging.log4j.core.source"/> <plugin id="org.apache.logging.log4j.core"/> <plugin id="org.apache.logging.log4j.slf4j2.impl.source"/> <plugin id="org.apache.logging.log4j.slf4j2.impl"/> <plugin id="org.osgi.service.http.whiteboard"/> <plugin id="org.apache.commons.commons-fileupload"/> <plugin id="org.eclipse.equinox.http.jetty"/> <plugin id="org.eclipse.equinox.http.jetty.source"/> <plugin id="org.eclipse.equinox.http.registry"/> <plugin id="org.eclipse.equinox.http.registry.source"/> <plugin id="org.eclipse.equinox.http.service.api"/> <plugin id="org.eclipse.equinox.http.servlet"/> <plugin id="org.eclipse.equinox.http.servlet.source"/> <plugin id="org.eclipse.equinox.http.servletbridge"/> <plugin id="org.eclipse.equinox.servletbridge"/> <plugin id="org.eclipse.jetty.ee8.security"/> <plugin id="org.eclipse.jetty.ee8.server"/> <plugin id="org.eclipse.jetty.ee8.servlet"/> <plugin id="org.eclipse.jetty.ee8.servlet.source"/> <plugin id="org.eclipse.jetty.servlet-api"/> <plugin id="org.eclipse.osgi.services"/> <plugin id="org.eclipse.osgi.services.source"/> <plugin id="org.eclipse.osgi.util.source"/> <plugin id="org.eclipse.persistence.jpa.jpql"/> <plugin id="org.eclipse.persistence.jpa.jpql.source"/> <plugin id="mariadb-java-client.source"/> <plugin id="mariadb-java-client"/> </includeBundles> <targetJRE path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-22"/> </target> This setup is not the minimal required version, but it does provide a fully functional EE8 base, because this is provided by the RAP 3.29 software site. Removing the dependencies on org.eclipse.equinox.http.registry in the plugin.xml file of my bundles, and replacing them with OSGI Whiteboard annotations proved relatively simple (you can see in the target definition above that this bundle is still present in RAP 3.29), and after some experimenting I could also implement my REST endpoints with this mechanism: Java import java.util.logging.Logger; import javax.servlet.Servlet; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.servlet.ServletContainer; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ServiceScope; @Component(service = Servlet.class, scope=ServiceScope.PROTOTYPE, property= "osgi.http.whiteboard.servlet.pattern=/" + RestServlet.S_CONTEXT_PATH + "/*") public class RestServlet extends ServletContainer { private static final long serialVersionUID = -478694508797364227L; public static final String S_CONTEXT_PATH = "my-context-path"; private Logger logger = Logger.getLogger(RestServlet.class.getName()); public RestServlet() { super( new RestApplication()); logger.info("STARTING SERVLET: " + this.getClass().getName()); } private static class RestApplication extends ResourceConfig { public RestApplication() { super(); property(ServerProperties.WADL_FEATURE_DISABLE, true); register( MyRestClass1.class ); register( MyRestClass2.class); ... } } } The biggest challenge, however, was replacing Gemini JPA and DBAccess to secure the database connection to EclipseLink in an OSGi container. Because this problem exposes a fundamental challenge in the entire migration to Java EE 11, I decided to share my solution with the DZone community to support others facing the same issues. EclipseLink and OSGI To understand the fundamental problem in this migration, it helps to briefly recap what sets OSGi apart from other container architectures. From the start, OSGI was based on strict sandboxing policies that other container architectures don't necessarily follow. Both EclipseLink and Jakarta EE don't specifically follow this regime, which means the code tends to cause problems when used in an OSGi environment. This can be very frustrating, because, yes, the libraries are OSGI bundles — basically JAR files with a META-INF/MANIFEST-MF file attached in order to instruct the container how the JAR is used- but this does not address the strict sandboxing policy provided by OSGI. In OSGi, every functionality that the bundle offers is invisible to other bundles unless it is specifically made available, usually through a declarative service. As EclipseLink does not use this mechanism, a bundle implementing a database client, such as for MySQL, H2, or MariaDB, will not be visible to EclipseLink, even though it is included in the target definition. This can be frustrating because everything looks fine, yet the system keeps telling you something is wrong with the database connection. There are a few ways to address this problem; a common approach is to wrap the bundle in a custom one that includes the declarative services needed to expose the required functionality, such as a database driver. Gemini JPA and DBaccess basically provide this service for EclipseLink. This approach, however, tends to become a maintenance hazard, as every updated version of the used bundle needs to be exposed in a corresponding wrapper bundle, so it is very hard to keep this up to date. Just to give the basic idea of what we need to achieve. EclipseLink scans for bundles on its classpath that have a persistence.xml file present (typically in the bundle's META-INF folder), which contains the necessary information about the datasource it should access. Most importantly, the file tells EclipseLink what database driver to look for. If another bundle implements this driver, EclipseLink can load it and open a connection to the database. In an OSGI container, the strict sandboxing policy creates two problems; EclipseLink cannot access the persistence.xml file EclipseLink cannot find a database client bundle Initially, I thought I would tackle this problem by updating the Git repos of Gemini JPA and DBAccess myself, but when I noticed the potential maintenance hazard of especially DBAccess, I decided to rethink this strategy. Since this problem is also potentially present in the migration of javax code to jakarta code, I decided to take a different approach better geared toward the eventual goal of this migration effort, and to my surprise, it proved simpler than I thought! The Solution What I wanted to achieve was to facilitate the normal behavior of EclipseLink as much as possible. This meant trying to expose the persistence.xml file to EclipseLink with as few modifications as possible, in order to prepare for the migration of javax.persistence to jakarta.persistence, which is going to affect the structure of this file. Secondly, I needed to expose the database client bundle (using MariaDB in this case) to EclipseLink in such a way that the solution could also be used for other clients, without any hard-coded references to them. Ideally, the bridge would get all the necessary information from the persistence.xml file and facilitate EclipseLink's normal discovery operation. The eventual bridge could be implemented as an abstract class that I could add to my bundle with core Java utilities: Java package org.mybundle.core.persistence import java.io.Closeable; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; import javax.persistence.EntityManagerFactory; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.eclipse.persistence.sessions.DirectConnector; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.wiring.BundleWiring; public class AbstractEntityManagerFactoryService implements Closeable{ public static final String S_PERSISTENCE_LOCATION = "META-INF/persistence.xml"; public static final String S_TARGET_DATABASE = "MySQL"; public static final String S_INFO_ENTITYMANAGER_CREATED = "EntityManagerFactory created"; public static final String S_INFO_MANAGED_ENTITY = "Managed entity: "; public static final String S_ERR_LOCATION_NOT_VISIBLE ="persistence.xml not visible to class loader"; public static final String S_ERR_LOCATION_NOT_FOUND = "Persistence unit myPU not found"; private String persistenceUnitName; private EntityManagerFactory emf; private Logger logger = Logger.getLogger( this.getClass().getName() ); protected AbstractEntityManagerFactoryService(String persistenceUnitName) { super(); this.persistenceUnitName = persistenceUnitName; } public EntityManagerFactory getFactory() { return emf; } /** * this method reads the persistence.xml provided by the bundle, and parses this. then it checks for corresponding * implementation of the databases driver (e.g mysql, mariadb or h2) and tries to offer this to the EclipseLink classloader * so that the regular service discovery can find it. * * @param context * @throws Exception */ protected void activate(BundleContext context) throws Exception { Bundle bundle = context.getBundle(); // Check 1: Is persistence.xml inside the bundle? URL entry = bundle.getEntry( S_PERSISTENCE_LOCATION); logger.info("Bundle resource: " + entry); // Check 2: Can the bundle class loader discover it? ClassLoader loader = bundle.adapt( BundleWiring.class).getClassLoader(); Enumeration<URL> resources = loader.getResources( S_PERSISTENCE_LOCATION ); int count = 0; while (resources.hasMoreElements()) { logger.info("Persistence descriptor: " + resources.nextElement()); count++; } if (count == 0) throw new IllegalStateException( S_ERR_LOCATION_NOT_VISIBLE); Properties jdbcProperties = PersistencePropertiesHandler.readPersistenceProperties(entry, persistenceUnitName); String driverName = jdbcProperties.getProperty( PersistenceUnitProperties.JDBC_DRIVER); emf = OsgiJdbcClassLoader.createFactory(context, driverName, persistenceUnitName, jdbcProperties); } public void close() { if (emf != null) { emf.close(); emf = null; } } } The neat trick is mainly carried out after Check 3. First we read the persistence.xml file in order to extract the properties: Java package org.mybundle.persistence; import java.io.InputStream; import java.net.URL; import java.util.Properties; import java.util.logging.Logger; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class PersistencePropertiesHandler { private static final String S_ERR_XML_MISSING = "Persistence descriptor not found"; private static final String S_ERR_UNIT_MISSING = "Persistence unit not found: "; private static final String S_INFO_PROPERTIES = "Persistence properties loaded for: "; private static Logger logger = Logger.getLogger(PersistencePropertiesHandler.class.getName()); public static Properties readPersistenceProperties( URL descriptor, String unitName) throws Exception { if (descriptor == null) { throw new IllegalStateException(S_ERR_XML_MISSING); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", true); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); try (InputStream input = descriptor.openStream()) { Document document = factory.newDocumentBuilder().parse(input); NodeList units = document.getElementsByTagNameNS( "*", "persistence-unit"); for (int i = 0; i < units.getLength(); i++) { Element unit = (Element) units.item(i); if (!unitName.equals(unit.getAttribute("name"))) { continue; } Properties properties = new Properties(); NodeList entries = unit.getElementsByTagNameNS("*", "property"); for (int j = 0; j < entries.getLength(); j++) { Element property = (Element) entries.item(j); properties.setProperty( property.getAttribute("name"), property.getAttribute("value") ); } logger.info(S_INFO_PROPERTIES + unitName); return properties; } } throw new IllegalStateException( S_ERR_UNIT_MISSING + unitName); } } Then the properties of the persistence.xml file are offered to a ClassLoaderFactory that tries to add the bundle of the database client to the classpath of EclipseLink: Java package org.mybundle.core.persistence; import java.sql.Driver; import java.util.Objects; import java.util.Properties; import java.util.logging.Logger; import javax.persistence.EntityManagerFactory; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.eclipse.persistence.jpa.PersistenceProvider; import org.eclipse.persistence.sessions.DirectConnector; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.wiring.BundleWiring; public final class OsgiJdbcClassLoader extends ClassLoader { private static final String S_INFO_DRIVER_LOADED = "The requested driver was successfully loaded: "; private static final String S_ERR_DRIVER_BUNDLE_NOT_FOUND = "The requested driver bundle wasn't found: "; private final Bundle driverBundle; private final String driverClassName; private static Logger logger = Logger.getLogger( OsgiJdbcClassLoader.class.getName() ); public OsgiJdbcClassLoader( ClassLoader parent, Bundle driverBundle, String driverClassName) { super(parent); this.driverBundle = Objects.requireNonNull(driverBundle); this.driverClassName = Objects.requireNonNull(driverClassName); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (driverClassName.equals(name)) { return driverBundle.loadClass(name); } throw new ClassNotFoundException(name); } public static EntityManagerFactory createFactory(BundleContext context, String driverName, String persistenceUnitName, Properties properties ){ DatasourceInspector inspector = new DatasourceInspector(); ClassLoader combinedLoader = null; EntityManagerFactory emf = null; try { Driver driver = inspector.findDriver(context, driverName); Bundle driverBundle = FrameworkUtil.getBundle(driver.getClass()); if (driverBundle == null) throw new IllegalStateException( S_ERR_DRIVER_BUNDLE_NOT_FOUND + driverName ); //Retrieve the parent classloader Bundle bundle = context.getBundle(); ClassLoader loader = bundle.adapt(BundleWiring.class).getClassLoader(); combinedLoader = new OsgiJdbcClassLoader( loader, driverBundle, driverName ); // Verify the bridge before starting EclipseLink. Class<?> resolvedDriver; resolvedDriver = Class.forName( driverName, true, combinedLoader); logger.info(S_INFO_DRIVER_LOADED + resolvedDriver.getName()); } catch (ReflectiveOperationException e) { e.printStackTrace(); return emf; } // Pass the combined loader to EclipseLink. properties.put( PersistenceUnitProperties.CLASSLOADER, combinedLoader ); // Tell EclipseLink to bypass DriverManager properties.put( PersistenceUnitProperties.JDBC_CONNECTOR, DirectConnector.class.getName()); Thread thread = Thread.currentThread(); ClassLoader previous = thread.getContextClassLoader(); try { thread.setContextClassLoader(combinedLoader); emf = new PersistenceProvider() .createEntityManagerFactory( persistenceUnitName, properties ); } finally { thread.setContextClassLoader(previous); } return emf; } } Here, we use an option provided by EclipseLink to use a custom classloader, which bypasses the default restrictions of OSGI. If a database driver is found, it will be present in the loader that we have just made and is offered to the classpath of EclipseLink. We need to overwrite two properties of the persistence.xml file in order to achieve this, but unless you have very specific requirements, this should not be a problem. You can just provide the structure that is recommended by the specifications, regardless of whether it's from OSGI or Jakarta. Lastly, a utility class is provided to assist in the workflow: Java package org.mybundle.persistence; import java.sql.Connection; import java.sql.Driver; import java.sql.SQLException; import java.util.Collection; import java.util.Properties; import java.util.logging.Logger; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.jdbc.DataSourceFactory; public class DatasourceInspector { private static final String S_INFO_JDBC_FACTORY = "Available JDBC factory: "; private static final String S_INFO_DRIVER_FOUND = "Found JDBC driver in bundle: "; private static final String S_ERR_DRIVER_NOT_FOUND = "JDBC driver not found: "; private static final String S_INFO_CONNECTED = "JDBC connection established with: "; private static final String S_ERR_CONNECTION = "JDBC driver did not accept the connection URL"; private Logger logger = Logger.getLogger(DatasourceInspector.class.getName()); /** * First find all the JDBC factories that are registered * @param context * @throws InvalidSyntaxException */ public void inspectJdbcFactories(BundleContext context) throws InvalidSyntaxException { Collection<ServiceReference<DataSourceFactory>> refs = context.getServiceReferences( DataSourceFactory.class, null); if ((refs == null) || ( refs.size() == 0)) { logger.info("No JDBC factories registered"); return; } for (ServiceReference<DataSourceFactory> ref : refs) { Object driver = ref.getProperty( DataSourceFactory.OSGI_JDBC_DRIVER_CLASS); logger.info(S_INFO_JDBC_FACTORY + driver); } } /** * Then find the JDBC driver with the given name * @param context * @param driverName * @return * @throws ReflectiveOperationException */ public Driver findDriver( BundleContext context, String driverName) throws ReflectiveOperationException { for (Bundle bundle : context.getBundles()) { if (bundle.getState() == Bundle.UNINSTALLED) continue; try { Class<?> type = bundle.loadClass(driverName); if (!Driver.class.isAssignableFrom(type)) continue; Bundle owner = FrameworkUtil.getBundle(type); if (owner != null && !owner.equals(bundle)) continue; logger.info(S_INFO_DRIVER_FOUND + bundle.getSymbolicName() ); return (Driver) type .getDeclaredConstructor() .newInstance(); } catch (ClassNotFoundException ex) { //logger.warning( ex.getMessage()); } } throw new IllegalStateException( S_ERR_DRIVER_NOT_FOUND + driverName ); } /** * Test the connection with the data source * @param driver * @param url * @param jdbcProperties * @throws SQLException */ public void testConnection( Driver driver, String url, Properties jdbcProperties) throws SQLException { try (Connection connection = driver.connect(url, jdbcProperties)) { if (connection == null) throw new SQLException(S_ERR_CONNECTION); logger.info( S_INFO_CONNECTED + connection.getMetaData().getDatabaseProductName()); } } } Lastly, we can now use the abstract class to gain access to the database in the bundle that provides the persistence.xml file, using a simple Component: Java package com.myorganisation.myservice; import javax.persistence.EntityManagerFactory; import org.mybundle.persistence.AbstractEntityManagerFactoryService; import org.osgi.framework.BundleContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; /** * Create the entity manager factory * @author Kees * */ @Component(immediate = true) public class EntityManagerService extends AbstractEntityManagerFactoryService{ public static final String BUNDLE_ID = "com.condast.indymo.authentication"; //Passes the entitymanager to other classes Dispatcher service = Dispatcher.getInstance(); public EntityManagerService() { super( BUNDLE_ID ); } @Activate public void activate( BundleContext context ) throws Exception { super.activate( context ); EntityManagerFactory emf = super.getFactory(); service.setEMF(emf); } @Deactivate public synchronized void close() { super.close(); service.disconnect(); } } Conclusion Although this approach has currently only been tested with MariaDB, I'm pretty sure it should also work with other database clients. It offers a lightweight solution that lets EclipseLink access database clients in an OSGi environment, bypassing the original solution offered by Gemini JPA and DBAccess. Moreover, it should already be prepared for the next step of the migration to jakarta.persistence.

By Kees Pieters
Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist
Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist

The first two parts of this series built a model before prescribing any tests. Part 1 argued that a test strategy for an asynchronous system has to start from two questions: which components and networks are really involved, and how asynchronous each connection really is. The same order-processing pipeline fell into three different regimes depending on where its boundary was drawn: a partially synchronous core region, an asynchronous, weak-notion-of-time edge made of multiple regions and offline mobile clients, and an asynchronous, no-notion-of-time batch integration with an external partner. A central idea was that a timeout is a trustworthy failure signal only to the degree that the system is synchronous. As timing guarantees weaken, we need to rely on different methods: logical ordering, message identity, and reconciliation. Part 2 then enumerated what can go wrong. Components can stop, pause, lose state, or misbehave. Networks can lose, duplicate, or reorder messages. Failures differ by where they can be handled (application level or platform level) and by how they recur (transient, intermittent, or permanent). Detection and mitigation are separate properties that deserve separate tests. Two findings carry directly into this part. First, no failure detector can be both complete and accurate over an unreliable, partially synchronous network, so some test flakiness is a correct reflection of that limit rather than a defect. Second, the failure-dominance matrix showed that message duplication, loss, and reordering weigh more heavily in the two regimes where timing is weakest. That is where this part begins. If messages can be lost, duplicated, and reordered, and a sender cannot tell a slow receiver from a malfunctioning receiver, then the main question is this: What can our system actually promise about each message, and how can we test that promise? This part covers three things, and Part 4 then brings the whole series together: Message delivery and processing semantics. Why delivery and processing are separate guarantees. Why exactly-once processing is impossible in the presence of failure. Why exactly-once processing semantics, built on idempotence, is the achievable and testable target. It also covers how to test idempotence as its own contract, and where common reliability claims stop: a TCP acknowledgment does not mean your application processed the data, and a broker's "exactly-once" feature does not extend to an external side effect such as a card charge.Observability as a testing prerequisite. Why diagnosing an asynchronous test failure needs correlated, cross-component tracing, and why causal identifiers are more trustworthy than timestamps.A practical test-design checklist. The framework from all three parts condensed into items you can lift into a test plan. Organized by component, network hop, operation, workflow, failure temporality, and scenario. The running example stays the same: an order-processing pipeline in which a payment service charges a customer's card. A duplicated charge is the failure this part keeps returning to. This is because it makes the difference between processing a message twice and having the system behave as though it processed it once easy to see. Message Delivery and Processing Semantics: Testing the Contract This is the area where imprecise language does the most damage, both in test names and assertions and in what gets promised to stakeholders. 1. Keep Delivery and Processing Separate Delivery is the network transferring a message and presenting it to a component. Processing is the receiver acting on it: generating a response and causing a side effect. Each gets the same three-way classification independently: at-most-once (zero or one time), at-least-once (one or more times), and exactly-once (exactly one time). A test asserting "exactly-once delivery" and one asserting "exactly-once processing" check different things. Conflating them is a common source of confusion when a suite has both a broker-level guarantee (delivery) and an idempotent-consumer guarantee (processing) layered together. Name tests to make the distinction explicit; for example, test_broker_at_least_once_delivery versus test_payment_handler_exactly_once_processing_semantics. 2. The Uncertainty That Senders Live In Between sending a request and receiving a response, a sender cannot distinguish among five situations: the request was lost, the receiver crashed before processing, the receiver crashed after processing, the response was lost, or the network or receiver is merely slow. Only a response returns the sender to certainty. Because a sender in that state has exactly two options, give up or try again, it is choosing between at-most-once and at-least-once behavior. Neither is exactly-once. Two naive attempts at exactly-once processing show why it is impossible in the presence of failure. If the receiver records the request and then processes it, a crash between the two steps means the retry is silently dropped: at-most-once. If the receiver processes the request and then records it, a crash between the two means the retry is processed again: at-least-once. There is always a gap, and a crash can occur within that gap. 3. Exactly-Once Semantics Is the Achievable, Testable Target What is achievable, and what "exactly-once" almost always means in a well-engineered system, is exactly-once processing semantics: the system behaves as though processing happened once even if it happened several times. This is because the extra attempts are idempotent and therefore equivalent in effect. It requires at-least-once delivery, at-least-once processing, and an idempotent processing step. Equivalence is application-defined: duplicate log lines are usually fine; a duplicate card charge is a problem. The test implication is that you should not assert that the handler was called exactly once. Assert that the side effect is equivalent regardless of how many times it was called. Python # Weak assertion: tests a guarantee that cannot exist assert handler.call_count == 1 # Correct assertion: tests the guarantee that can exist deliver_duplicate(message, times=5) assert account.balance == expected_balance_after_single_charge assert payment_gateway.charge_count == 1 # deduplicated via idempotency key A myth worth busting: TCP is a reliable protocol, but it does not extend that reliability to your application. TCP guarantees delivery to the receiving kernel's buffer and acknowledges it before the application has read and processed the data. A crash between the acknowledgment and the application's processing silently turns what looked like at-least-once delivery into message loss at the application layer. At-least-once delivery at a lower layer does not entail at-least-once delivery at a higher one. Note also that some brokers offer "exactly-once" features (Kafka's idempotent producers and transactions are an example). These give strong guarantees within the broker's own boundary, for instance for read-process-write cycles between Kafka topics. They do not extend to an external side effect such as a card charge or an email, which remains your responsibility. Read the fine print of any exactly-once claim: what boundary does the guarantee cover? 4. Testing Idempotence Directly Idempotence, f(f(x)) = f(x), is what makes at-least-once processing acceptable. It should be tested as its own explicit contract, independent of the rest of the business logic. A minimal test matrix per state-changing operation: Single call. Call once and record the resulting state.Duplicate call. Repeat with the identical request and idempotency key; assert the state is unchanged.Concurrent duplicates. Fire N identical requests simultaneously (a thread pool or async gather). Assert the state is equivalent to one successful call and that the downstream side effect (the real payment gateway charge) happened once, not N times.Crash at the boundary. Simulate a crash between the side effect and the recording of the idempotency key. Then retry, and assert that the side effect is not duplicated and the key is eventually recorded. The common implementation pattern is an idempotency key: the sender generates a UUID and attaches it to the request and every retry. The receiver deduplicates on it. Payment processors such as Stripe support idempotency keys in their APIs and replay the stored result for a repeated key. On the receiving side, the safe pattern is to record the key and perform the side effect in one transaction. Commit only if the key was new (for example via a uniqueness constraint on a keys table). Crash injection at the idempotency boundary. The naive implementations fail at exactly one point: the gap between the side effect and the durability record. That gap is tiny in wall-clock time, but it is where interesting production bugs can live. It can be tested deterministically if you can fault-inject at that specific boundary rather than at the whole-request level: Code-level fault injection lets you inject a fault, a delay, or a simulated crash at a specific method or line, without modifying the code under test. That makes "crash between the database write and the key write" a repeatable test rather than a hope that a random chaos experiment lands there.If the implementation uses the transactional recording pattern, the most valuable test may not be fault injection at all. It may be a plain integration test proving that the transaction boundary actually wraps both operations. A simple test at the right level can beat an elaborate chaos experiment. 5. Testing Consumer-Side Deduplication Against Real Brokers Use Testcontainers with a real Kafka, RabbitMQ, or similar broker rather than mocking the broker client. Duplicate-delivery semantics are broker-specific: Kafka's at-least-once behavior with manual offset commits differs from SQS's visibility-timeout redelivery, which differs from RabbitMQ's ack and nack handling. A mock encodes your assumptions about the broker. The real broker encodes its actual behavior, and the actual behavior is exactly what you are trying to test against. Consume a message, process it, crash the consumer before committing the offset, restart it, and assert that the redelivered message produces an equivalent (not doubled) side effect. 6. Beyond Hand-Written Examples for Message Handlers Idempotence tests written by hand cover the cases someone thought of. Several other techniques cover the rest, and each is cheap at the level where it applies: Property-based testing generates sequences of messages, with duplicates, reorderings, and crashes interleaved, and checks invariants such as "the final state is the same as if each message had been processed once, in a valid order". It finds orderings nobody would have written down.Fuzzing and malformed-input testing target the poison-message problem: a message that is structurally invalid, oversized, or valid but nonsensical must be routed to a dead-letter path without crashing the consumer or blocking the partition behind it.Contract and schema-compatibility testing treat messages as contracts. Consumers lag, replay old messages, and run old versions during deploys, so a message written last month must still be readable today. Consumer-driven contracts verify that a producer still satisfies what each consumer relies on, and compatibility checks verify that new and old schema versions can coexist.Reconciliation testing is the safety net for message loss: a comparison of what was sent with what was acknowledged that reports anything missing, duplicated, or conflicting. It matters most where no timeout can decide, as in the batch scenario of Part 1.Approval (snapshot) testing guards the shape of serialized messages against accidental change. Part 4 places each of these at the level where it pays off. Observability as a Testing Prerequisite For async systems, you cannot write good tests, or diagnose failing ones, without correlated cross-component observability. A single logical operation spans multiple components' local state and multiple network hops. None of them is visible from any one component's logs. A minimum viable setup for testing: Distributed tracing with OpenTelemetry, with trace context propagated through message headers and not only HTTP headers. This is the highest-leverage investment for diagnosing async test failures. It exposes the actual causal chain (the happened-before relationship) across components instead of forcing you to reconstruct it from timestamps in separate log files.Structured logging with a correlation ID on every log line in every component, as a baseline even without full tracing.Traces captured during fault-injection windows, not just on failure. The interesting bugs are often in the recovery path, which appears only if you capture the whole timeline and not just the final assertion failure.Logical ordering, not timestamps. When correlating events across components, prefer causal identifiers (trace and span relationships, Kafka offsets within a partition, per-key sequence numbers) over wall-clock timestamps, which cannot be compared across components without accounting for skew.Tests that assert on traces. Beyond diagnosing failures, a test can assert on the causal path itself: that the spans for each service exist in causal order and that a second charge never appears. This checks the end state and the path that led to it, and it checks that observability itself works. A Practical Test-Design Checklist The framework, condensed into something you can lift into a test plan. Before Writing Any Test ☐ Map the components and networks involved (Part 1, section 2). Do not assume the logical architecture diagram is the real one. ☐ Classify each network hop's degree of synchrony (Part 1, section 3). This decides whether timeout-based assertions are valid for that hop. ☐ Identify which of the three scenarios (or which composition) your system actually is (Part 1, section 3.4), and prioritize the failure cells according to which failures dominate in your scenario (Part 2). For Each Component ☐ Crash-Stop test: kill and verify graceful degradation. ☐ Omission test: pause and resume, verify correct resumption. ☐ Crash-Recovery test: kill with partial state loss, verify that durable state is actually durable. For Each Network Hop ☐ Message loss test. ☐ Message duplication test. ☐ Message reordering test. For Each State-Changing Operation ☐ Idempotence matrix (section 1.4): single call, duplicate call, concurrent duplicates, crash at the boundary. ☐ An explicit exactly-once-processing-semantics assertion on the resulting state, not on the call count. For Each Multi-Step or Multi-Component Workflow ☐ Compensation test: fail partway through and verify correct rollback, including a failing compensation. ☐ Retry test: verify that the backoff strategy matches the assumed failure temporality (transient, intermittent, permanent). Temporal Coverage ☐ At least one transient-failure (single-shot) test per failure type. ☐ At least one intermittent-failure test per critical path, using scheduled recurring faults or soak testing. ☐ At least one permanent-failure test verifying escalation and alerting rather than infinite retry. Per Scenario ☐ Scenario 1: boundary-value tests around every timeout; a load-plus-degradation test that checks for retry storms. ☐ Scenario 2: property-based tests of merge logic with skewed clocks; a long partition test with reconciliation after healing; a device test with a wrong clock. ☐ Scenario 3: malformed and duplicate file tests; a reconciliation test for every "missing, duplicated, conflicting" case; production reconciliation alerts with a defined grace period. Observability ☐ Trace context propagated through asynchronous messages, not only synchronous calls. ☐ Traces captured during fault-injection windows, not only at the final assertion. Wrapping Up There are four main ideas in this part. First, delivery and processing are different guarantees: exactly-once processing is impossible in the presence of failure. Exactly-once processing semantics, built on at-least-once delivery and idempotence, is the target worth testing, with assertions on resulting state rather than on call counts. Second, idempotence deserves its own contract: a single call, a duplicate call, concurrent duplicates, and a crash between the side effect and its record. Third, messages are contracts that outlive the code that wrote them, so schema compatibility, contract tests, malformed-input tests, and reconciliation belong beside the idempotence tests. Fourth, you cannot diagnose or assert on asynchronous behavior without correlated tracing and causal identifiers instead of timestamps. Part 4 brings the series together. It lists the techniques that apply at each level (unit, API, system) and explains how they help in each of the three regimes.

By Stelios Manioudakis DZone Core CORE
Spring AI Migration: From the Vertex AI Gemini Module to the Google GenAI SDK
Spring AI Migration: From the Vertex AI Gemini Module to the Google GenAI SDK

If your Spring Boot application talks to Gemini on Google Cloud, a Spring AI migration is already on your backlog, whether you have scheduled it or not. Google deprecated the generative AI part of the Vertex AI SDK in favor of the Google Gen AI SDK. Recent Vertex AI SDK releases print a deprecation warning in build logs, and Google has said those functions will be removed from SDK versions during 2026. At Cloud Next 2026, the Vertex AI product itself was folded into the Gemini Enterprise Agent Platform. Spring AI followed its upstream. Spring AI 2.0 reached general availability in June 2026 and consolidated the Google providers around the Gen AI SDK. The current Spring AI reference now sends readers of the old integration to a section headed "Migration from Vertex AI Gemini," and its wording is blunt: if you were previously using spring-ai-vertex-ai-gemini, migrate to Google GenAI. Check your own build before you plan the work. The old module was still being published as recently as the 1.1 line and the 2.0 milestones, so depending on which version you are on today, you may see a deprecation warning rather than a build failure. Either way, the destination is the same, and the sooner you move, the less you carry. The migration is mechanical, but it touches five separate things, and two of them fail quietly rather than loudly. This article walks through each one in order. What a Spring AI Migration Touches Moving off the old module touches five things, and they surface at very different times. What changesWhen you noticeThe artifact idAt build time, as a warning or a resolution failureThe package and class namesAt compile timeThe property keysAt startup, or silently as defaultsThe authentication modeAt the first call, as a permission errorTool calling behaviorAt runtime, in a flow you may not have tested The first two are easy, because the compiler finds them for you. The last three are the ones that cost an afternoon, so most of this article is about those. Step 1: Swap the Dependency Start with the build file. The chat starter changes name completely. Replace this: XML <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-vertex-ai-gemini</artifactId> </dependency> Add this: XML <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-google-genai</artifactId> </dependency> Artifact names on the Google side have shifted more than once, so search your build file for vertex rather than trusting one name. Older projects may carry spring-ai-vertex-ai-gemini-spring-boot-starter, and the manual configuration dependency spring-ai-vertex-ai-gemini may be there as well. Note that Spring AI 2.0 targets Spring Boot 4.0 and 4.1 and moves to Jackson 3. So this is not an isolated dependency change. Plan the Spring Boot upgrade and the Spring AI upgrade as one piece of work rather than two. Step 2: Update the Imports and Class Names Next, fix the code. The package moved, and the client class is different. The old code used Google's Vertex AI SDK directly: Java import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatModel; import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatOptions; import com.google.cloud.vertexai.VertexAI; VertexAI vertexApi = new VertexAI(projectId, location); var chatModel = new VertexAiGeminiChatModel(vertexApi, VertexAiGeminiChatOptions.builder() .model("gemini-2.0-flash") .temperature(0.4) .build()); The new code uses the Gen AI SDK. The package is org.springframework.ai.google.genai, and the underlying client is com.google.genai.Client rather than com.google.cloud.vertexai.VertexAI. For most applications, you will not construct the model by hand at all, because the starter auto-configures it. Therefore, the practical change in a typical Spring Boot service is deleting code rather than rewriting it. Inject ChatClient and let the starter supply the model. Java @RestController class AnswerController { private final ChatClient chatClient; AnswerController(ChatClient.Builder builder) { this.chatClient = builder.build(); } @GetMapping("/answer") String answer(@RequestParam String question) { return chatClient.prompt(question).call().content(); } } If you do build the model manually, the embedding side has a documented equivalent. GoogleGenAiEmbeddingConnectionDetails replaces VertexAiEmbeddingConnectionDetails, and GoogleGenAiTextEmbeddingModel replaces the old embedding model class. Step 3: Rename Every Property This is the step that fails quietly, because an unrecognized property is usually ignored rather than rejected. Your application starts, uses defaults, and behaves differently from yesterday. Two things changed at once. The prefix moved from spring.ai.vertex.ai.gemini to spring.ai.google.genai, and Spring AI 2.0 removed the .options segment from property keys across the whole project. Old keyNew keyspring.ai.model.chat=vertexaispring.ai.model.chat=google-genaispring.ai.vertex.ai.gemini.project-idspring.ai.google.genai.project-idspring.ai.vertex.ai.gemini.locationspring.ai.google.genai.locationspring.ai.vertex.ai.gemini.credentials-urispring.ai.google.genai.credentials-urispring.ai.vertex.ai.gemini.chat.options.modelspring.ai.google.genai.chat.modelspring.ai.vertex.ai.gemini.chat.options.temperaturespring.ai.google.genai.chat.temperaturespring.ai.vertex.ai.gemini.chat.options.top-kspring.ai.google.genai.chat.top-kspring.ai.vertex.ai.gemini.chat.options.max-output-tokensspring.ai.google.genai.chat.max-output-tokens So a working configuration now looks like this: Properties files spring.ai.google.genai.project-id=my-project spring.ai.google.genai.location=us-central1 spring.ai.google.genai.chat.model=gemini-2.5-flash spring.ai.google.genai.chat.temperature=0.5 Watch the model default while you are here. The old module defaulted to gemini-2.0-flash and the new one defaults to gemini-2.5-flash. If you never set the model explicitly, your application changes model on upgrade without telling you. Set it explicitly either way, so the choice is recorded in your repository rather than in a release note. Step 4: Pick Your Authentication Mode Deliberately The new client supports two completely different backends, and one property decides which one you get. Set api-key and the client calls the Gemini Developer API with that key.Leave api-key unset, supply project-id and location, and the client calls Vertex AI using Google Cloud credentials. Consequently, a team that sets both during testing will find their service account permissions ignored, because the API key wins. The symptom is a permission error that mentions the wrong project, or quota that comes off the wrong account. For a service running on Google Cloud, you almost always want the second mode, so that the workload uses its own service account rather than a key someone pasted into a config file. Properties files # Vertex AI mode, using the workload's own credentials spring.ai.google.genai.project-id=my-project spring.ai.google.genai.location=us-central1 Make sure no GOOGLE_API_KEY or spring.ai.google.genai.api-key is set anywhere in the environment. Check your container image, your deployment manifest, and any .env file that gets mounted. Step 5: Migrate Embeddings as Well Teams usually remember the chat model and forget the embeddings, which then break at the next vector store write. The embedding starter changes too: XML <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-google-genai-embedding</artifactId> </dependency> The properties follow the same pattern as before, with the old spring.ai.vertex.ai.embedding prefix becoming spring.ai.google.genai.embedding: Properties files spring.ai.model.embedding.text=google-genai spring.ai.google.genai.embedding.project-id=my-project spring.ai.google.genai.embedding.location=us-central1 spring.ai.google.genai.embedding.text.model=text-embedding-004 spring.ai.google.genai.embedding.text.task-type=RETRIEVAL_DOCUMENT One important warning. If you change the embedding model or the number of dimensions during this migration, every vector already in your store becomes meaningless, because the new vectors live in a different space. So either keep the model identical, or plan a full reindex. Do not discover this from a search that quietly returns irrelevant documents. Step 6: Check Your Tool Calling Spring AI 2.0 also moved tool calling out of the individual chat models and into the advisor chain. A ToolCallingAdvisor is now registered automatically and runs the loop that each model used to run for itself. For most applications this is invisible. However, if your old configuration used internal-tool-execution-enabled or the older proxy-tool-calls property to control who executes the tool, that behavior now lives somewhere else. Review any code that deliberately intercepted tool calls instead of letting the framework run them. Therefore, the practical advice is to treat tool calling as a separate verification item rather than assuming the migration covered it. Step 7: Verify the Spring AI Migration Before You Deploy Finally, prove the migration rather than assuming it. Three checks are enough. First, confirm which model answered. The response metadata carries it: Java ChatResponse response = chatClient.prompt("hello").call().chatResponse(); System.out.println(response.getMetadata().getModel()); System.out.println(response.getMetadata().getUsage().getTotalTokens()); Second, confirm which identity made the call. Look at the Google Cloud audit logs for the request and check that the principal is the service account you expect, not a key. Third, confirm that no property was silently dropped. Start the application with the failure switch on so unknown keys are reported instead of ignored: Shell java -jar app.jar --spring.config.ignore-unknown-properties=false Run that once in a staging environment. It is the fastest way to find a spring.ai.vertex.ai.gemini.* key that somebody left in a profile file. Conclusion This Spring AI migration is unusual in that it comes from two directions at once. Google deprecated the generative AI part of the Vertex AI SDK in favor of the Gen AI SDK, and Spring AI consolidated its Google support around the same SDK. Neither direction is going to reverse, so the old path has no future, even where it still resolves today. The work itself is a few hours. Swap the starter, fix the imports, rename the properties, decide your authentication mode on purpose, migrate the embeddings, and check tool calling. The parts that cost teams a day are the quiet ones: a renamed property that defaults instead of failing, a stray API key that overrides the service account, and an embedding model change that invalidates an existing index. Do those three checks and the rest is straightforward. Further Reading Google GenAI Chat, Spring AI ReferenceGoogle GenAI Text Embeddings, Spring AI ReferenceSpring AI 2.0.0 GA announcementGemini Enterprise Agent Platform release notes

By Garima Agarwal
Part 5: Automated Agent Evaluation and Regression Testing for MCP Tool Services
Part 5: Automated Agent Evaluation and Regression Testing for MCP Tool Services

The Core Problem In Part 1, we built a Quarkus MCP tool server with Jakarta Bean Validation. In Part 2, we secured it with agentgateway. In Part 3, we added distributed tracing. In Part 4, we orchestrated multi-agent workflows with A2A. The architecture works, it is secure, and it is observable — but how do you know it stays correct across code changes? Manual testing with Goose catches obvious breakages. Ask it to debug a customer, and if the tool throws an exception, you will notice. But manual testing has structural gaps that compound as the codebase grows: No systematic coverage. Developers test the happy path — CUST-4091 returns ACTIVE — but skip the edge cases. What about CUST-9999 (not found)? What about CUST-7734 (suspended)?No regression detection. A refactor that accidentally changes ENTERPRISE_TIER to ENTERPRISE in getCustomerStatus will not be caught until an agent downstream makes a wrong decision based on that string.No validation boundary testing. The @Pattern(regexp = "^CUST-[0-9]{4,8}$") constraint on customerId is the security boundary between LLM hallucinations and your business logic. If someone relaxes it — or removes it during a refactor — you need to know immediately.No workflow-level testing. A multi-step agent workflow like "debug customer CUST-4091 -> check region health -> verify SLA" chains three tool calls where each step depends on the previous result. Unit tests on individual tools cannot catch integration breakages. The solution is an evaluation framework that treats MCP tool services like any other API. Define expected inputs and outputs in golden datasets, run them automatically, and fail the build if accuracy drops. Architecture The Eval Runner is a standalone Quarkus application that: Loads golden datasets from JSON files defining expected tool inputs, outputs, and error conditions.Connects to the MCP server via raw HTTP using the same JSON-RPC protocol that Goose uses.Executes test cases — calling each tool and comparing results against golden expectations.Generates evaluation reports with accuracy, latency percentiles (p50/p95/p99), and per-case pass/fail details.Exposes a REST API so evaluations can be triggered programmatically from CI/CD pipelines. Prerequisites Everything from Part 1, plus Part 1 MCP server built — cd part1-quarkus-mcp && mvn package -DskipTests Step 1: Designing Golden Datasets Golden datasets are JSON files that define expected behavior for MCP tools. Each file targets a different kind of verification. We define three dataset types that cover the full testing surface. Tool Accuracy: Verifying Correct Output The tool-accuracy.json suite tests each MCP tool with known inputs and verifies exact field matches in the output: JSON { "name": "tool-accuracy", "description": "Verify correct output for each MCP tool with known inputs", "cases": [ { "id": "customer-active-enterprise", "description": "Active enterprise customer returns correct status and region", "tool": "getCustomerStatus", "arguments": {"customerId": "CUST-4091"}, "expect": { "customerId": "CUST-4091", "status": "ACTIVE", "tier": "ENTERPRISE_TIER", "primaryRegion": "US-EAST-1" } }, { "id": "zone-health-entries", "description": "Zone health returns exactly 6 diagnostic entries", "tool": "getZoneHealthLogs", "arguments": {"zoneId": "US-EAST-1"}, "expectCount": 6 } ] } The expect field runs a partial match — only the listed fields are checked, so the test is resilient to new fields being added. The expectCount field verifies array length without inspecting individual entries. Validation Boundary: Testing Security Constraints The validation-boundary.json suite verifies that Jakarta Bean Validation rejects malformed inputs at the MCP boundary: JSON { "name": "validation-boundary", "description": "Verify Jakarta Bean Validation rejects malformed inputs at the MCP boundary", "cases": [ { "id": "customer-sql-injection", "description": "SQL injection payload rejected by pattern constraint", "tool": "getCustomerStatus", "arguments": {"customerId": "'; DROP TABLE users; --"}, "expectError": true, "errorContains": "must match" }, { "id": "audit-xss-payload", "description": "XSS payload in customer ID rejected by pattern constraint", "tool": "getAuditTrail", "arguments": {"customerId": "<script>alert(1)</script>"}, "expectError": true, "errorContains": "must match" } ] } Setting expectError: true means the test passes only if the tool returns an error. The errorContains field verifies the error message includes the expected validation message (e.g., "must match" from @Pattern). This catches two classes of regression: constraints being removed entirely, and constraints being relaxed to accept wider input. Workflow Regression: Testing Multi-Step Agent Behavior The workflow-regression.json suite tests the multi-step sequences that AI agents execute. Each workflow chains tool calls where outputs from one step feed into the next: JSON { "name": "workflow-regression", "description": "Verify multi-step agent workflows produce correct chained results", "workflows": [ { "id": "customer-debug-workflow", "description": "Debug customer: lookup status, check region health, verify SLA", "steps": [ { "id": "lookup-customer", "tool": "getCustomerStatus", "arguments": {"customerId": "CUST-4091"}, "expect": {"status": "ACTIVE", "primaryRegion": "US-EAST-1"}, "extractField": "primaryRegion", "extractAs": "region" }, { "id": "check-region-health", "tool": "getZoneHealthLogs", "arguments": {"zoneId": "${region}"}, "expectCount": 6 }, { "id": "verify-sla", "tool": "getSLACompliance", "arguments": {"serviceId": "api-gateway"}, "expect": {"compliancePct": 99.97, "violationCount": 0} } ] } ] } The extractField and extractAs fields enable variable passing between steps. In this workflow, step 1 extracts primaryRegion from the getCustomerStatus result and stores it as region. Step 2 uses ${region} in its arguments — the eval runner substitutes the extracted value before calling the tool. This mirrors exactly what Goose does when it chains tool calls: read a result, extract a value, pass it to the next tool. Assertion Types Summary AssertionFieldsPurposeExact matchexpectVerify specific field values in tool output.CountexpectCountVerify array length (zone health logs, audit events).ErrorexpectError + errorContainsVerify validation rejects input with correct message.Workflow chainingextractField + extractAsPass output from one step as input to the next. Step 2: Building the MCP Eval Client The eval client needs to speak with the MCP wire protocol — JSON-RPC over Streamable HTTP, the same transport Goose and agentgateway use. We could hand-roll that with java.net.http.HttpClient: build the JSON-RPC envelope, manage an incrementing request ID, send an initialize handshake, and parse responses that arrive as either plain JSON or Server-Sent Events (data:-prefixed lines). That's ~60 lines of protocol plumbing that has nothing to do with evaluation. Instead, we reuse the managed McpClient from quarkus-langchain4j-mcp — the exact extension Part 4 introduced for agent-to-tool calls. The transport, handshake, and SSE-vs-JSON handling all disappear into the extension: Java @ApplicationScoped public class McpEvalClient { @Inject @McpClientName("mcp-under-test") McpClient mcpClient; @Inject ObjectMapper mapper; public String callTool(String toolName, Map<String, Object> arguments) throws Exception { // The managed client caches discovery and refreshes it on tool-list changes. mcpClient.listTools(); String argsJson = mapper.writeValueAsString(arguments); try { var result = mcpClient.executeTool( ToolExecutionRequest.builder() .name(toolName) .arguments(argsJson) .build()); if (result.isError()) { throw new ToolRejectedException(result.resultText()); } return result.resultText(); } catch (ToolExecutionException e) { // The current client throws for isError results. Its protocol // exceptions carry an error code; transport failures use other types. if (e.errorCode() != null) throw e; throw new ToolRejectedException(e.getMessage()); } } public JsonNode callToolAsJson(String toolName, Map<String, Object> arguments) throws Exception { String text = callTool(toolName, arguments); if (text == null || text.isBlank()) { return mapper.createObjectNode(); } JsonNode parsed = parseText(text); if (!parsed.isTextual()) return parsed; // Part 1 encodes list items as separate MCP text blocks. LangChain4j // joins those blocks with newlines (plain log lines or JSON audit events). // Strict parsing above prevents Jackson from silently keeping only the // first audit event when several JSON objects arrive together. var lines = text.lines().toList(); if (lines.size() > 1) { var items = mapper.createArrayNode(); lines.forEach(line -> items.add(parseText(line))); return items; } return mapper.valueToTree(Map.of("text", text)); } private JsonNode parseText(String text) { try { return mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(text); } catch (JsonProcessingException e) { return mapper.getNodeFactory().textNode(text); } } public static class ToolRejectedException extends Exception { public ToolRejectedException(String message) { super(message == null ? "MCP tool returned an error" : message); } } public int getToolCount() { return mcpClient.listTools().size(); } } The managed client handles initialization and the wire protocol. Call listTools() before execution so the client has tool metadata; subsequent calls use its cache. Handle both isError() results and the client’s ToolExecutionException representation of tool rejections. Protocol errors and wrapped transport failures remain evaluation failures. Part 1 returns list entries as separate text blocks. The client's default extractor joins them with newlines, so this lab reconstructs those log lines and JSON audit events into arrays. Strict JSON parsing prevents silently retaining only the first audit event. This parser matches Part 1's text-only outputs; richer or multiline content needs an extractor that preserves the original block boundaries. The validation suite passes only for a tool rejection with the expected message. Transport failures always fail the case. Part 1's quarkus-mcp-server-hibernate-validator integration keeps the constraints active and returns concise validation messages instead of internal-error stack traces. Startup should report 12/12, 8/8, and 8/8. CI also runs part5-evaluation/smoke.py against the real packaged services to verify all three suites. The client is configured declaratively in application.properties — no endpoint parsing code, just point the named client at any MCP-compatible server: Properties files # The MCP server under test (Part 1 directly) quarkus.langchain4j.mcp.mcp-under-test.transport-type=streamable-http quarkus.langchain4j.mcp.mcp-under-test.url=http://localhost:8080/mcp # Through agentgateway (Part 2) — just change the URL: # quarkus.langchain4j.mcp.mcp-under-test.url=http://localhost:3000/mcp Step 3: Implementing the Evaluation Engine The EvalRunner loads golden datasets, executes each case, and generates reports. Data Model The evaluation framework uses four Java records: Java @JsonIgnoreProperties(ignoreUnknown = true) public record EvalCase( String id, String description, String tool, Map<String, Object> arguments, JsonNode expect, boolean expectError, Integer expectCount, String errorContains, String extractField, String extractAs) { } @JsonIgnoreProperties(ignoreUnknown = true) public record EvalSuite( String name, String description, List<EvalCase> cases, List<WorkflowCase> workflows) { @JsonIgnoreProperties(ignoreUnknown = true) public record WorkflowCase( String id, String description, List<EvalCase> steps) { } } public record EvalResult( String caseId, String tool, boolean passed, long latencyMs, JsonNode actual, JsonNode expected, String error) { public static EvalResult pass(String caseId, String tool, long latencyMs, JsonNode actual) { return new EvalResult(caseId, tool, true, latencyMs, actual, null, null); } public static EvalResult fail(String caseId, String tool, long latencyMs, JsonNode actual, JsonNode expected, String error) { return new EvalResult(caseId, tool, false, latencyMs, actual, expected, error); } } The EvalReport record calculates aggregate metrics from the list of results: Java public record EvalReport( String suiteName, String timestamp, int total, int passed, int failed, double accuracy, LatencyStats latency, List<EvalResult> results) { public record LatencyStats(long p50, long p95, long p99, long max) { } public static EvalReport from(String suiteName, List<EvalResult> results) { int passed = (int) results.stream() .filter(EvalResult::passed).count(); int total = results.size(); double accuracy = total > 0 ? (double) passed / total * 100.0 : 0.0; List<Long> latencies = results.stream() .map(EvalResult::latencyMs) .sorted() .toList(); LatencyStats stats = latencies.isEmpty() ? new LatencyStats(0, 0, 0, 0) : new LatencyStats( percentile(latencies, 50), percentile(latencies, 95), percentile(latencies, 99), latencies.getLast()); return new EvalReport(suiteName, Instant.now().toString(), total, passed, total - passed, accuracy, stats, results); } private static long percentile(List<Long> sorted, int p) { int idx = Math.min( (int) Math.ceil(p / 100.0 * sorted.size()) - 1, sorted.size() - 1); return sorted.get(Math.max(0, idx)); } } Core Evaluation Logic The EvalRunner service handles both individual cases and multi-step workflows: Java @ApplicationScoped public class EvalRunner { @Inject McpEvalClient client; @Inject ObjectMapper mapper; public EvalReport runSuite(String name) throws Exception { EvalSuite suite = loadSuite(name); List<EvalResult> results = new ArrayList<>(); if (suite.cases() != null) { for (EvalCase evalCase : suite.cases()) { results.add(runCase(evalCase)); } } if (suite.workflows() != null) { for (EvalSuite.WorkflowCase workflow : suite.workflows()) { results.addAll(runWorkflow(workflow)); } } return EvalReport.from(suite.name(), results); } For individual test cases, the runner calls the MCP tool, checks for errors, then applies the appropriate assertion: Java private EvalResult runCase(EvalCase evalCase) { long start = System.currentTimeMillis(); try { JsonNode response = client.callTool( evalCase.tool(), evalCase.arguments()); long latency = System.currentTimeMillis() - start; // Check for JSON-RPC error if (response.has("error")) { String errorMsg = response.path("error") .path("message").asText(""); if (evalCase.expectError()) { if (evalCase.errorContains() != null && !errorMsg.contains(evalCase.errorContains())) { return EvalResult.fail(evalCase.id(), evalCase.tool(), latency, response.get("error"), null, "Error message does not contain: " + evalCase.errorContains()); } return EvalResult.pass(evalCase.id(), evalCase.tool(), latency, response.get("error")); } return EvalResult.fail(evalCase.id(), evalCase.tool(), latency, response.get("error"), null, "Unexpected error: " + errorMsg); } // Parse content and apply assertions JsonNode content = response.path("result").path("content"); JsonNode actual = parseContent(content); if (evalCase.expectCount() != null) { int count = actual.isArray() ? actual.size() : 1; if (count != evalCase.expectCount()) { return EvalResult.fail(evalCase.id(), evalCase.tool(), latency, mapper.valueToTree(Map.of("count", count)), mapper.valueToTree(Map.of("count", evalCase.expectCount())), "Expected " + evalCase.expectCount() + " items, got " + count); } return EvalResult.pass(evalCase.id(), evalCase.tool(), latency, actual); } if (evalCase.expect() != null) { String mismatch = compareFields(actual, evalCase.expect()); if (mismatch != null) { return EvalResult.fail(evalCase.id(), evalCase.tool(), latency, actual, evalCase.expect(), mismatch); } } return EvalResult.pass(evalCase.id(), evalCase.tool(), latency, actual); } catch (Exception e) { long latency = System.currentTimeMillis() - start; return EvalResult.fail(evalCase.id(), evalCase.tool(), latency, null, evalCase.expect(), "Exception: " + e.getMessage()); } } Workflow Variable Substitution Multi-step workflows maintain an extraction map. After each step, if extractField and extractAs are specified, the runner pulls the named field from the result and stores it for use in subsequent steps: Java private List<EvalResult> runWorkflow( EvalSuite.WorkflowCase workflow) { List<EvalResult> results = new ArrayList<>(); Map<String, String> extractions = new HashMap<>(); for (EvalCase step : workflow.steps()) { Map<String, Object> resolvedArgs = new HashMap<>(); for (var entry : step.arguments().entrySet()) { String val = String.valueOf(entry.getValue()); for (var ext : extractions.entrySet()) { val = val.replace("${" + ext.getKey() + "}", ext.getValue()); } resolvedArgs.put(entry.getKey(), val); } EvalCase resolved = new EvalCase( workflow.id() + "/" + step.id(), step.description(), step.tool(), resolvedArgs, step.expect(), step.expectError(), step.expectCount(), step.errorContains(), step.extractField(), step.extractAs()); EvalResult result = runCase(resolved); results.add(result); if (result.passed() && step.extractField() != null && step.extractAs() != null && result.actual() != null) { JsonNode val = result.actual() .path(step.extractField()); if (!val.isMissingNode()) { extractions.put(step.extractAs(), val.asText()); } } } return results; } In the customer-debug-workflow, this produces the following execution: getCustomerStatus("CUST-4091") returns primaryRegion: "US-EAST-1" -> extracted as regiongetZoneHealthLogs("${region}") resolves to getZoneHealthLogs("US-EAST-1") -> verifies 6 entriesgetSLACompliance("api-gateway") -> verifies compliancePct: 99.97 If step 1's output changes — say primaryRegion is renamed to region — step 2 will fail because the extraction produces null. This catches exactly the kind of cross-tool contract breakage that unit tests miss. Field Comparison The compareFields method does partial matching — it only checks fields present in the expect object: Java private String compareFields(JsonNode actual, JsonNode expected) { Iterator<String> fields = expected.fieldNames(); while (fields.hasNext()) { String field = fields.next(); JsonNode expectedVal = expected.get(field); JsonNode actualVal = actual.path(field); if (actualVal.isMissingNode()) { return "Missing field: " + field; } if (expectedVal.isNumber() && actualVal.isNumber()) { if (expectedVal.doubleValue() != actualVal.doubleValue()) { return "Field " + field + ": expected " + expectedVal + ", got " + actualVal; } } else if (!expectedVal.asText() .equals(actualVal.asText())) { return "Field " + field + ": expected " + expectedVal.asText() + ", got " + actualVal.asText(); } } return null; } This means you can add new fields to tool responses without breaking existing golden tests — only the fields you explicitly check are asserted. Step 4: Exposing the REST API The evaluation engine is wrapped in a Quarkus REST resource so it can be triggered programmatically: Java @Path("/eval") @Produces(MediaType.APPLICATION_JSON) public class EvalResource { @Inject EvalRunner runner; @GET @Path("/suites") public List<String> listSuites() { return runner.listSuites(); } @GET @Path("/suites/{name}") public EvalSuite getSuite(@PathParam("name") String name) throws Exception { return runner.loadSuite(name); } @POST @Path("/run/{suite}") public EvalReport runSuite(@PathParam("suite") String suite) throws Exception { return runner.runSuite(suite); } } EndpointMethodPurpose/eval/suitesGETList available golden suite names/eval/suites/{name}GETGet suite details including all test cases/eval/run/{suite}POSTExecute a suite and return the evaluation report Configure the eval runner to listen on port 8083 (separate from the MCP server on 8080): Properties files quarkus.http.port=8083 # CORS for demo SPA quarkus.http.cors=true quarkus.http.cors.origins=/.*/ # Managed MCP client (quarkus-langchain4j-mcp) — the server under test quarkus.langchain4j.mcp.mcp-under-test.transport-type=streamable-http quarkus.langchain4j.mcp.mcp-under-test.url=http://localhost:8080/mcp Step 5: Running the Interactive Demo Start all services with the one-command script: Shell cd part5-evaluation ./start-all.sh The script builds Part 1 and Part 5, starts the MCP server on :8080, the eval runner on :8083, and the demo SPA on :8891. Open the MCP Evaluation Console at http://localhost:8891/index.html and walk through the four demo steps: Initialize - Connects to the MCP server at :8080, verifies all 5 tools are discoverable. The architecture diagram animates the connection between the Eval Console, the Eval Runner, and the MCP Server.Load Suite - Select a golden dataset from the dropdown (tool-accuracy, validation-boundary, or workflow-regression). The test cases appear in a table showing case ID, tool name, and description.Run Evaluation - Executes each test case against the MCP server via the eval runner. Watch the results appear in real time with pass/fail indicators. The stat tiles update live: total cases, passed, failed, accuracy percentage, and average latency.View Report - Shows the complete evaluation report with accuracy score, latency percentiles (p50/p95/p99/max), and a detailed results table. Click any failed case to inspect the raw JSON showing expected vs. actual values. Step 6: Integrating With CI/CD Command-Line Evaluation Run evaluations against a live MCP server using curl: Shell # Run the tool-accuracy suite curl -s -X POST http://localhost:8083/eval/run/tool-accuracy | \ python3 -c " import sys, json r = json.loads(sys.stdin.read()) print(f\"Suite: {r['suiteName']}\") print(f\"Accuracy: {r['accuracy']}%\") print(f\"Passed: {r['passed']}/{r['total']}\") print(f\"Latency p50: {r['latency']['p50']}ms p99: {r['latency']['p99']}ms\") if r['failed'] > 0: for t in r['results']: if not t['passed']: print(f\" FAIL: {t['caseId']} - {t['error']}\") sys.exit(1) " Full Regression Script Run all three suites and fail if any test case does not pass: Shell #!/usr/bin/env bash set -euo pipefail EVAL_HOST="${1:-http://localhost:8083}" EXIT_CODE=0 for suite in tool-accuracy validation-boundary workflow-regression; do echo "Running $suite..." REPORT=$(curl -s -X POST "$EVAL_HOST/eval/run/$suite") ACCURACY=$(echo "$REPORT" | python3 -c \ "import sys,json; print(json.loads(sys.stdin.read())['accuracy'])") FAILED=$(echo "$REPORT" | python3 -c \ "import sys,json; print(json.loads(sys.stdin.read())['failed'])") echo " Accuracy: $ACCURACY% ($FAILED failures)" if [ "$FAILED" -gt 0 ]; then echo " FAILED" EXIT_CODE=1 fi done if [ "$EXIT_CODE" -eq 0 ]; then echo "All suites passed." else echo "Regression detected — see failures above." exit 1 fi GitHub Actions Integration Add evaluation as a CI step that runs on every push and pull request: YAML name: MCP Eval on: [push, pull_request] jobs: eval: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: java-version: '25' distribution: 'temurin' - name: Build MCP server and eval runner run: mvn package -DskipTests -pl part1-quarkus-mcp,part5-evaluation - name: Start MCP server run: | QUARKUS_OTEL_SDK_DISABLED=true \ java -jar part1-quarkus-mcp/target/quarkus-app/quarkus-run.jar & sleep 5 - name: Start eval runner run: | java -jar part5-evaluation/target/quarkus-app/quarkus-run.jar & sleep 5 - name: Run all evaluation suites run: | for suite in tool-accuracy validation-boundary workflow-regression; do echo "=== $suite ===" curl -sf -X POST http://localhost:8083/eval/run/$suite | \ python3 -c " import sys, json r = json.loads(sys.stdin.read()) print(f\" {r['passed']}/{r['total']} passed ({r['accuracy']}%)\") assert r['accuracy'] == 100.0, \ f\"{r['suiteName']}: {r['failed']} failures\" " done Coming Up in Part 6: Model Routing and Failover Part 6: Model Routing and Failover with Agent Router adds a 30-minute lab with deterministic model stubs. Apply this chapter's testing approach to routing, fallback, retry boundaries, and recovery. The existing MCP suites continue to validate tool behavior; the new HTTP smoke checks validate model-traffic behavior. Neither set evaluates generated answer quality. Parts 1–5 remain runnable without Agent Router or model-provider credentials.

By Daniel Oh DZone Core CORE
Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment
Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment

Fraud rings are closed loops of payments: account A pays B, B pays C, and C pays A, usually for almost the same amount, and often within hours. Ordinary traffic produces loops by chance, so finding a loop is easy, and deciding whether it is a ring is the hard part. This article builds a small experiment around that question. We generate a synthetic payments dataset in Snowflake with a known set of rings and a deliberate set of decoys. We find every candidate loop with a SQL query that runs in the database. We then ask a hosted model (Jev from TypeSafe AI) to judge each loop twice: once with a bare question, and once with a guided question that explains what to look for. Finally, we score both answers against the hidden ground truth and compare them with two plain rules that use no model at all. The short answer: guidance matters a great deal, and a well-crafted rule is a strong contender. Read on for more details, including a few things that went wrong on the way. What We Are Building The project is two Jupyter notebooks that run on your own machine and connect to Snowflake remotely: The first notebook creates the ACCOUNTS and TRANSACTIONS tables, with planted rings and decoys.The second notebook finds candidate loops in SQL, asks the model to judge a sample of them and scores the answers. The flow for each run looks like this: The generator writes the data to Snowflake and reads it back to check it.The triage notebook runs a self-join query in Snowflake that returns every closed loop of three or four accounts, with its timing and amount ratio computed in the database.Each loop becomes a small record: the amounts, the minutes between transfers, the account risk scores and a few summary numbers. The record holds no account ids, customer names, transaction ids or fraud label.The model answers a bare question and a guided question for each loop in a sample.We score the answers against the IS_FRAUD_RING label, which the model never sees. The notebooks support three model modes: hosted (Jev over the internet), local (a model served by Ollama on your machine), and replay (answers saved from an earlier hosted run, so the notebook runs with no model access). All results in this article come from the hosted model. Prerequisites You'll need: Python and Jupyter on your machine, running in a virtual environment (venv).A Snowflake account and a role that can create a database and a warehouse. SYSADMIN works.Key-pair login set up for your Snowflake user (refer to the Gotchas section).A TypeSafe API key for hosted mode. Replay mode needs no key. Set the following environment variables before launching Jupyter: Shell export SNOWFLAKE_ACCOUNT="<your-account-identifier>" export SNOWFLAKE_USER="<your-user>" export SNOWFLAKE_PRIVATE_KEY_PATH="rsa_key.p8" export SNOWFLAKE_ROLE="SYSADMIN" export SNOWFLAKE_WAREHOUSE="FRAUD_RING_WH" export TYPESAFE_API_KEY="<your-api-key>" The database defaults to FRAUD_RING_DEMO and the schema to PUBLIC. Set SNOWFLAKE_DATABASE or SNOWFLAKE_SCHEMA to change them. If your key has a passphrase, set the SNOWFLAKE_PRIVATE_KEY_PASSPHRASE as well. Newer Snowflake accounts may block single-factor password login, so key-pair login is the safer choice. Creating the Key-Pair Generate a private key in PKCS8 format and derive the public key from it using OpenSSL: Shell openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub The first command writes the private key to rsa_key.p8, which is the file SNOWFLAKE_PRIVATE_KEY_PATH points to. Keep it secret and never commit it to the repository. If you would rather protect it with a passphrase, remove -nocrypt from the first command. OpenSSL will then prompt for a passphrase, and you must also set SNOWFLAKE_PRIVATE_KEY_PASSPHRASE. Registering the Public Key Print the public key body on one line, without the header and footer lines: Shell grep -v "PUBLIC KEY" rsa_key.pub | tr -d '\n' Copy that output. Paste only this key body into Snowflake, leaving out the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines. Then set it on your user: SQL SET my_username = CURRENT_USER(); ALTER USER IDENTIFIER($my_username) SET RSA_PUBLIC_KEY='<your-public-key>'; To confirm the registration, check that the user now has a key fingerprint: SQL DESC USER IDENTIFIER($my_username); Look for a value in the RSA_PUBLIC_KEY_FP row. You may need to run ALTER USER as a role that can modify your user, such as SECURITYADMIN or ACCOUNTADMIN. The Two Snowflake Tables The generator creates two tables. Both are fully synthetic and the same seed always produces the same data: TableColumnsACCOUNTSACCOUNT_ID, CUSTOMER_NAME, RISK_SCORETRANSACTIONSTX_ID, SOURCE_ACCOUNT_ID, TARGET_ACCOUNT_ID, AMOUNT, TIMESTAMP, DESCRIPTION, IS_FRAUD_RING TIMESTAMP is a real TIMESTAMP_NTZ, and IS_FRAUD_RING is the text 'True' or 'False'. Every transfer that belongs to a real ring is flagged there, which gives us the ground truth. The default dataset has 1,000 accounts and 50,000 background transactions, which are random transfers between random accounts. The loops are added on top. The first dataset ends up with 50,271 transactions, 191 of them real-ring transfers in 45 real rings. Transaction IDs are assigned after everything is shuffled together, so an ID says nothing about whether a transfer belongs to a ring. Each loop uses its own accounts, and no account appears in two loops. The Rings and the Decoys An easy dataset would not teach us much. In our first version, the guided question and a simple timing rule both scored 100 percent, which told us the data was too easy. So the generator plants five kinds of loops: KindCountTimingAmountsAccount RiskReal Ring?ring33Minutes apartWithin about 3%0.35 to 0.95Yeslookalike10Minutes apartWithin about 3%0.05 to 0.55Nouneven_fast10Minutes apartAt least 10% apart0.01 to 0.99Noslow_ring6One to three days apartWithin about 3%0.35 to 0.95Yesuneven_ring6Minutes apartAbout 4% to 14% apart0.60 to 0.95Yes The kinds are chosen so that no single signal separates rings from decoys: A timing rule finds the fast, near-equal rings but also the look-alikes, and it misses the slow rings.Equal amounts alone catch the look-alikes too.Risk scores overlap between real rings and look-alikes in the 0.35 to 0.55 band.A tight amount cut-off misses the moderately uneven real rings. The hard cases are on by default. In the data generator notebook, set INCLUDE_HARD_CASES = False to get only the real rings. Finding Candidate Loops in SQL The triage notebook does not ask the model to find loops. Snowflake does that with a self-join on the transactions table. For three-account loops, the query looks like the following, trimmed for space: SQL WITH in_window AS ( SELECT tx_id, source_account_id, target_account_id, amount, timestamp, is_fraud_ring FROM FRAUD_RING_DEMO.PUBLIC.TRANSACTIONS WHERE amount > 3000.0 AND amount < 10000.0 ) SELECT t1.tx_id, t2.tx_id, t3.tx_id, ... FROM in_window t1 JOIN in_window t2 ON t1.target_account_id = t2.source_account_id JOIN in_window t3 ON t2.target_account_id = t3.source_account_id WHERE t3.target_account_id = t1.source_account_id AND t1.source_account_id < t2.source_account_id AND t1.source_account_id < t3.source_account_id AND t2.source_account_id <> t3.source_account_id The query starts each loop at its lowest account ID, so it finds every loop once. The outer query adds the span in hours, the ratio of the largest to the smallest amount, and a flag for whether every leg is labeled as fraud. That flag is the ground truth, and it is never sent to the model. By default, the notebook searches for rings of three and four accounts. The search takes under a second on an X-Small warehouse. Larger rings can produce tens of thousands of candidates, so the MAX_AMOUNT_RATIO keeps the search small if you raise HOPS_MAX. On the first dataset, the search returns 861 candidates: 165 three-account loops and 696 four-account loops. Only 24 of them (2.8 percent) are real rings. The rest are chance loops and decoys. What the Model Sees Each loop becomes a small record. The following shows one of the sampled loops: JSON { "context": "A closed cycle of money transfers between bank accounts: each account pays the next one, and the last pays the first.", "accounts_in_cycle": 4, "transfers": [ {"hop": 1, "amount": 9627.21, "minutes_after_first_transfer": 89}, {"hop": 2, "amount": 9681.66, "minutes_after_first_transfer": 155}, {"hop": 3, "amount": 9733.96, "minutes_after_first_transfer": 244}, {"hop": 4, "amount": 9724.9, "minutes_after_first_transfer": 0} ], "account_risk_scores": [0.59, 0.62, 0.58, 0.68], "average_account_risk": 0.62, "total_span_hours": 4.07, "largest_to_smallest_amount_ratio": 1.011 } In hosted mode, this record is what leaves your machine. It holds amounts, minutes between transfers, risk scores, and the account count. It does not hold account IDs, customer names, transaction IDs, or the fraud label. The Questions We ask three questions. The first two are choices, and the third is a score. The bare question gives the model the record and asks whether it looks like a deliberate money-laundering ring or a coincidental cycle, with no hint about what separates them. The model can answer likely_ring, coincidental_cycle, or needs_review. The guided question asks the same thing, but tells the model what to weigh. It gives rough bands for the amount ratio and the average risk and says that timing is only a hint: Python GUIDED_QUESTION = Choice( instructions=( "Does this cycle of transfers look like a deliberate money-laundering ring, or a coincidental cycle " "in ordinary traffic? Judge it on amounts and risk together.\n" "Amounts: largest_to_smallest_amount_ratio up to about 1.03 is near-equal. Up to about 1.15 is moderately " "uneven. Above about 1.15 is clearly uneven, and then it is not a ring whatever the risk says.\n" "Risk: average_account_risk above 0.45 is high, below 0.35 is low, and between 0.35 and 0.45 is middling.\n" "Decide like this. Amounts up to about 1.15 and high risk: a ring. Near-equal amounts and low risk: a " "legitimate cycle. Only a middling average risk: needs review.\n" "Timing is only a hint. Many rings finish within hours, but some take days between transfers, so a long " "span alone does not rule a ring out." ), criteria={ ... }, ) The urgency score asks how soon an investigator should look at a loop using the same bands. The notebook ranks loops by this, but this article does not evaluate that ranking. The Baselines A model call is only worth it if the call beats a rule, or does something a rule cannot. We compare against two rules that use no model: The timing rule flags a loop when its span is within 24 hours, and its amount ratio is within 1.032.The amounts and risk rule ignores timing, flags a loop when its amount ratio is within 1.032, and its average account risk is at least 0.5. The second rule is deliberately strong. We added it after seeing that the data was separable on those two features. The model is compared against the best simple alternative, not against a weak one. The Sample We do not send all 861 candidates to the model. The notebook sends a sample of 100 loops, built in three steps: Send all the real rings, up to half the sample.Send the most tricky non-rings, which are loops that finish within the rule's time window without being real rings. These take up to 30 percent of the sample.Send a random draw from everything else. The second step matters more than it looks. When we first sampled the non-rings at random, the timing rule scored a perfect 1.0 on the sample, and 0.68 on all candidates. The look-alike decoys seldom landed in the sample. Reserving part of the sample for fast non-rings fixed that. The rules now score the same on the sample as on the full population. So the sample represents the difficulty. The sample for the first dataset held all of the 24 real rings and 12 fast non-rings. Running the Notebooks Run the generator first. It connects, creates the database and warehouse if they are missing, and then: Checks that the two tables do not already exist,Generates the data,Loads it with write_pandas, Reads it back and compares row counts, the number of real-ring transfers, the sum of the amounts, and the earliest and latest timestamps. You should see: Plain Text FRAUD_RING_DEMO.PUBLIC is ready: 50,271 transactions, 191 of them in 45 real rings. Then run the triage notebook. Set MODE to hosted, local or replay in section 3. A 100-loop sample takes a few seconds per question with the hosted model. At the end of the run, the notebook can save the hosted answers to a replay file. You can rerun the whole comparison later with no model access. To rerun a notebook against existing tables, note that the generator will stop with a plain message and change nothing. To replace them, set REPLACE_TABLES_IN to the exact target, for example "FRAUD_RING_DEMO.PUBLIC", and run again. The notebook lists the tables with their row counts and confirms the role can create tables before it replaces anything. Set the variable back to None afterwards. The Held-Out Dataset The guidance contains numbers, such as 1.15 and 0.45, which we chose after looking at the first dataset. That raises an obvious question: does the guidance work only because it was tailored to this data? To test that, each notebook has a HELDOUT switch. In the generator, HELDOUT = True builds a second dataset with a different seed and shifted ranges. Real-ring risk drops to 0.30 to 0.90, look-alike risk rises to 0.10 to 0.60, and the moderately uneven rings are slightly more uneven. The data is written to its own schema (HELDOUT) so the first dataset stays in place. In the triage notebook, HELDOUT = True reads from that schema and keeps a separate replay file. The guidance is not retuned. The second dataset has 50,267 transactions, 186 real-ring transfers and 854 candidate loops (of which 27 are real rings). Results on the First Dataset The following table displays the results on the 100-loop sample. A loop counts as flagged when the answer is likely_ring: MethodFlaggedReal Rings CaughtFalse AlarmsPrecisionRecallBare question3723 of 24140.6220.958Guided question2523 of 2420.9200.958Timing rule2517 of 2480.6800.708Amounts and risk rule1919 of 2401.0000.792 The bare question method finds 23 of the 24 real rings, but pay for it with 14 false alarms (compared to 2 for the guided question). The guided question catches four more real rings than the amounts and risk rule, at the cost of two false alarms. It also finds the slow rings and the moderately uneven rings that the other rules miss. This is because the guidance tells it that timing is only a hint, and that moderately uneven amounts can still be a ring. The timing rule is the weakest. It misses seven real rings and raises eight false alarms. There is one more comparison worth looking at. If every needs_review answer goes to a person: MethodLoops Sent to a PersonReal Rings ReachedFalse AlarmsGuided question, flagged or sent to review2924 of 245Amounts and risk rule1919 of 240 The guided question reaches all 24 real rings, and a person opens 29 loops to do it. The amounts and risk rule reaches 19 of 24 from 19 loops. Whether the extra ten loops are worth the five extra rings depends on what a missed ring costs. Results on the Held-Out Dataset Here is the same notebook run against the held-out schema, with no change to the guidance: MethodFlaggedReal Rings CaughtFalse AlarmsPrecisionRecallBare question3324 of 2790.7270.889Guided question2826 of 2720.9290.963Timing rule2519 of 2760.7600.704Amounts and risk rule2322 of 2710.9570.815 The shape of the result is the same. The guided question lands at 0.929 precision and 0.963 recall, against 0.920 and 0.958 for the first dataset. It catches four more real rings than the amounts and risk rule, against one more false alarm. Sent for review, the guided question reaches all 27 real rings from 31 loops, while the amounts and risk rule catches 22 of 27 from 23 flagged. What Went Wrong on the Way The guidance went through several versions, and the numbers show why we did not stop at the first one. The samples differ between rows, so read the table as indicative: GuidanceGuided PrecisionGuided RecallWhat HappenedTiming-based: a span over a day is a coincidence0.9440.850Missed every slow ring. Matched the timing rule.Amounts and risk, in words0.9470.900Better, but flagged a loop with a ratio of 1.20.Bands, with "high risk" meaning scores mostly above 0.61.0000.333Over-cautious. Sent 16 of 24 real rings to review.Bands on the average risk, with 0.45 as high0.9200.958The final version. The third row is the instructive one. The model followed our bands faithfully, and the bands were wrong. Our real rings start at a risk of 0.35, so a threshold of 0.6 put most of them in the middling band, and the model compliantly sent them to review. The fix was twofold. We added an average_account_risk field to each record (so the model does not have to do the arithmetic), and we put the high threshold at 0.45, where the data actually separate. A language model applies the thresholds you give it literally. If they are wrong, the answers will be wrong consistently and decisively. Conclusions On two synthetic datasets, built with different seeds and different risk ranges, we found the following: Guidance is worth more than the model alone. The same model, asked the same question with and without guidance, cuts false alarms from 14 to 2 on the first dataset and from 9 to 2 on the second, at equal or better recall.The guided model beats the best simple rule on recall. It catches four more real rings than the amounts and risk rule on both datasets, including the slow and moderately uneven rings that a tight cut-off cannot find.The rule keeps the edge on precision. With zero or one false alarm, the amounts and risk rule is the more precise method, and it needs no model.A mixed answer is useful. Counting needs_review as an escalation, the guided question reaches every real ring on both datasets, which a rule with a cut-off cannot do.The sample should reflect the difficulty. A random sample of non-rings hides the decoys and flatters the rules. Caveats Synthetic data. The data have the structure we gave them. These results show that guidance carries across draws of the same generator, not that it works on real transactions.Small samples. Each run has 24 to 27 real rings, so a difference of a loop or two is noise. The model's answers can also shift a little between runs: the bare question gave 22, and then 23 real rings were caught on the same data.The guidance is tuned to the data. The bands encode the generator's ranges. The held-out test shows they survive a shift, but it was modest, and we did not retune.Only the hosted model was measured. The local mode (which uses a small Ollama model) exists in the notebook, but we did not run its results here.The urgency score is unevaluated. The notebook ranks loops by it, but we did not assess the ranking.A rule can be strict. Two features and two thresholds got within a few false alarms of the model, so a rule is the baseline to beat, not a strawman.One search window. The query finds only loops with transfers between 3,000 and 10,000, and three or four accounts. Rings outside that window are not candidates. Gotchas These cost us the most time, and they are worth knowing about before you run the notebooks: Password login can be blocked. Newer Snowflake accounts reject single-factor password login with an "incorrect username or password" error even when the password is right. Set up key-pair login and set SNOWFLAKE_PRIVATE_KEY_PATH. A relative path works if the key file sits next to the notebook.The role that creates the database owns it. Objects created by ACCOUNTADMIN are not usable by SYSADMIN. Use one role (such as SYSADMIN) for both notebooks, and a new database name, rather than a pre-existing database owned by another role.Replacing tables is guarded. The generator never drops a table by default. REPLACE_TABLES_IN must match the target exactly, and the notebook checks that the role can create tables before it replaces anything. We added this after an earlier version dropped tables before discovering it lacked the privilege to recreate them.Timestamp parsing. TRY_TO_TIMESTAMP_NTZ accepts text only. The triage query wraps the column in TO_VARCHAR so it works whether the column is text or a real timestamp.Replay files are tied to the question and the sample. They are keyed by loop and question, so if you change the guidance or the sample, the saved answers are stale. Delete the replay file and record a new one. Each dataset has its own replay file, so the two datasets do not clash.Stops are quiet. When a notebook stops deliberately (e.g., because the tables already exist), it prints a message instead of an error warning. Real failures, such as missing privileges, still raise errors.Leave REPLACE_TABLES_IN as None. Set it only for the run that needs it, then set it back. Summary We built a small Snowflake experiment around one question: when you ask a model whether a loop of payments is a fraud ring, how much would it help to tell the model what to look for? On a synthetic dataset with decoys and hard cases, the bare question caught nearly every real ring but raised 14 false alarms. The guided question kept the recall and cut the false alarms to 2. On a second dataset, with a different seed and shifted ranges, the same guidance gave 0.929 precision and 0.963 recall. A well-chosen rule is a serious competitor. The amounts and risk rule was the most precise method on both datasets, and the guided model beat it only on recall and its ability to send mixed cases to a person. The model's value here is not that it replaces a rule. It's that it handles the cases cut-off rules miss, once you tell it what matters. The practical lesson is to treat the guidance as part of the system. Test it on a dataset you did not tune it on. Check that the sample shows the hard cases. Read the thresholds as carefully as the code. A missed ring and a needless review do not cost the same, and the right method depends on which one you can afford. The full source code is available on GitHub.

By Akmal Chaudhri DZone Core CORE
API Regression Testing for Event-Driven Systems: Catching Breaking Changes in Async APIs
API Regression Testing for Event-Driven Systems: Catching Breaking Changes in Async APIs

An event payload is an API, even if nobody on the team calls it one. The moment an order.created message lands on a Kafka topic, and three other services start reading it, that payload has consumers, a contract, and a long memory. Change it carelessly and something downstream breaks, often hours later, often in a service whose owners didn’t know the event had changed at all. Most API regression testing practice grew up around HTTP. Send a request, compare the response to a baseline, flag the difference. Async APIs don’t fit that shape neatly. There’s no response to compare; the consumer might process the message much later, and the breaking change might not even be in the schema. Teams that run heavily event-driven architectures tend to learn this the hard way, so it’s worth looking at what API regression testing needs to cover when the API is a stream of messages. Why Async APIs Break Differently With an HTTP API, a regression usually shows up quickly. A client calls an endpoint, gets an unexpected response, and fails right there. Events loosen that feedback loop in a few ways. Producers and consumers deploy independently, so a producer change can sit on a topic for days before an older consumer version reads it. Consumers often process messages asynchronously, so failures surface as stuck consumer groups, dead-letter queues, or quietly wrong data rather than clean errors. And a single topic frequently has consumers the producing team has never heard of, like an analytics pipeline, a search indexer, or a team’s experimental service. The result is that event regressions tend to be discovered late and far from their cause. That’s exactly the situation regression testing is supposed to prevent. What Schema Compatibility Checks Catch The first line of defense for many teams is a schema registry. Confluent Schema Registry, for example, lets each subject enforce a compatibility mode. Backward compatibility means consumers using the new schema can still read data written with the previous one. Forward compatibility means consumers still on the old schema can read data written with the new one. Full compatibility requires both. There are transitive variants that check against all previous versions, not just the latest. These checks are genuinely valuable. Try registering a schema that drops a field consumers still read, or swaps a type for something incompatible, and the registry simply refuses, so the bad version never reaches the topic. For Avro and Protobuf payloads especially, that catches a big chunk of structural breakage without anyone having to remember to look. Teams using plain JSON without a registry don’t get this enforcement at all, which is one reason JSON event payloads tend to drift more than schema-managed ones. AsyncAPI specifications can document the contract, but documentation alone doesn’t stop a breaking change from shipping. What Schema Checks Miss Here’s where API regression testing has to go further. A schema describes structure. A lot of real event regressions are about meaning, and those sail straight through compatibility checks. A field called amount switches from cents to dollars. Same name, same type, fully compatible schema, and every consumer that sums amounts is now off by a factor of a hundred. A status enum gains a new value that older consumers don’t handle, so their switch statements fall through to a default branch nobody tested. A timestamp moves from UTC to local time. An optional field that was always populated in practice starts arriving empty because of an upstream refactor. Some regressions aren’t even in the payload. Take the message key. Change it, and in Kafka the events start landing on different partitions, so the per-key ordering consumers counted on quietly goes away. Or a retry tweak ends up producing more duplicates than before, and suddenly it matters whether consumers were actually idempotent or just never tested for it. A refactor starts emitting two events where there used to be one. None of these show up as schema violations. They show up as wrong numbers in a dashboard, or a customer charged twice. Using Real Messages as the Regression Baseline So how do you catch problems the schema can’t see? The same way HTTP regression testing does, really. You keep a picture of what known-good behavior looked like, and every change gets compared against it. In an event-driven system, that picture comes from real message traffic. Start with producers. Grab the inputs that make a service publish something, plus whatever it actually published in response. Once someone changes the service, feed it those same inputs again and line up its new messages against the old ones. Amounts in different units, an enum value nobody’s seen before, a different key, an event that wasn’t there last time: it all pops out as a difference, and a “compatible” schema doesn’t hide any of it. On the consumer side, it works in reverse. Recorded messages from the real topic get replayed into the new consumer version, and the test checks what the consumer does with them: the database writes it makes, the downstream calls it sends, the events it publishes in turn. A consumer that suddenly mishandles a message it processed fine last week gets caught before deploy rather than in production. Recording at the network level makes this considerably easier, since application code doesn’t need instrumenting to capture broker traffic. Keploy, an open-source tool, takes this approach, capturing Kafka and RabbitMQ traffic alongside HTTP calls and database queries and replaying the recorded interactions as mocks, which lets a service’s event behavior be checked in CI without a live broker. The Tradeoffs Worth Knowing About Message-based regression baselines are powerful, but they come with real costs, and teams adopting them tend to run into the same few. Noise is louder than in HTTP. Event payloads are full of values that differ every run: event IDs, timestamps, correlation IDs, sometimes broker metadata like offsets. Without careful field-level ignore rules, every comparison looks like a regression. What tends to save teams is being stingy with those rules. Ignore one specific field at a time, never a whole payload, and leave a short note on each rule explaining why it’s there, because six months later nobody will remember.Ordering often isn’t stable. Say a service fires off a few events at once. They might show up in one order today and a different one tomorrow, and that’s not a bug. So the comparison has to know where order genuinely matters, like within one key’s stream, and where it’s fine to shrug.Payloads often carry sensitive data. Real events frequently include customer details. Recording from production, or from staging copies of production data, means redacting before anything is stored, and redacting to stable placeholder values so relationships between events survive.Volume needs sampling. High-throughput topics produce far more messages than a regression suite needs. Teams typically sample by event type and by edge case, aiming for coverage of distinct behaviors rather than raw volume.Baselines age. An intentional change to an event means re-recording, and that update deserves the same review as the code change. Otherwise “intended” quietly becomes “whatever the last recording said.” Where Contract Tests Fit In Consumer-driven contract testing covers some of the same ground from a different angle. Pact is a good example. With its message pacts, each consumer writes down the message shape it’s expecting, and the producer’s build checks that it can still produce exactly that. When teams can coordinate like this, it works well, and getting consumer expectations written down is worth a lot. Contract tests and recorded baselines tend to complement each other. Contracts capture what consumers say they need. Recorded traffic captures what actually flows through the system, including the unofficial consumers and undocumented fields that contracts never mention. Teams with many independent consumers often find the second category is where the surprises live. A Practical Layering Pulling this together, event-driven API regression testing usually ends up layered. Schema compatibility checks in the registry block structurally breaking changes at publish time. Contract tests make known consumer expectations explicit. Recorded message baselines, replayed in CI against new producer and consumer versions, catch the semantic and behavioral changes the other two layers can’t see. And in production, monitoring dead-letter queues and consumer lag gives an early warning when something still slips through. No single layer covers everything, and that’s the point. Each one catches a different kind of regression at a different cost. Conclusion Event-driven systems don’t remove API contracts. They just make them easier to forget, because nobody calls an endpoint and nobody gets an immediate error. Schema registries handle structural safety well, but the regressions that hurt most in async systems are usually about meaning: units, enums, keys, ordering, and duplicates. API regression testing for async APIs has to compare behavior, not just shapes. The topics most worth protecting first are the ones with the most consumers and the least visibility into who those consumers are. Those are where a compatible-looking change is most likely to break something nobody was watching.

By Sancharini Panda
Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution
Building Fault-Tolerant MCP Servers With Temporal for Durable AI Agent Execution

AI agents are increasingly invoking tools that take longer than a single network request and depend on systems that can fail independently of the agent runtime. A Model Context Protocol (MCP) tool may trigger document generation, code analysis, data synchronization, or infrastructure automation. It may also trigger another operation that runs for minutes rather than milliseconds. Treating such work as an ordinary request-response handler creates a fragile coupling between the lifetime of the MCP connection and the lifetime of the underlying operation. Temporal provides a different execution model: the MCP server can accept a tool request, start a durable Workflow, return a stable execution identifier, and allow later requests to retrieve the result. The operation can then survive MCP client restarts, HTTP disconnects, Worker crashes, transient dependency failures, and process redeployments without restarting completed steps. Temporal calls this model Durable Execution because Workflow progress is reconstructed from persisted Event History when execution moves between Workers. The following examples use the Temporal Java SDK (current published version:1.40.0), together with the MCP Java SDK 2.2.0, which added support for the stateless MCP 2026-07-28 specification. The snippets are documentation-aligned illustrative code and were not executed as part of this article. Java String workflowId = "agent-job-" + request.executionKey(); WorkflowOptions options = WorkflowOptions.newBuilder() .setWorkflowId(workflowId) .setTaskQueue("agent-execution") .build(); AgentWorkflow workflow = workflowClient.newWorkflowStub(AgentWorkflow.class, options); WorkflowClient.start(workflow::run, request); return new StartResult(workflowId, "RUNNING"); Temporal requires a Task Queue when creating a new Workflow stub, and a business-derived Workflow ID is preferable when the same logical request must not create duplicate executions. A Workflow ID identifies the logical Workflow across client interactions and can be used to reconnect to an existing execution instead of tying identity to an MCP socket, HTTP request, or process-local object. This pattern also handles duplicate MCP submissions more cleanly. Retries can occur at proxies, clients, agent frameworks, or application layers. If every retry invents a new Workflow ID, one logical agent instruction can start several independent executions. Deriving the ID from a stable request key moves deduplication into the orchestration boundary. Temporal documents the same principle for durable operations that may be started more than once: stable IDs should be derived from request identity or operation input so retries reuse the intended execution rather than duplicating side effects. Durable Progress Belongs Inside the Workflow A Temporal Workflow should contain orchestration state, branching decisions, timers, and durable coordination, while external calls belong in Activities. Workflow code is replayed from history, so nondeterministic side effects such as HTTP requests, database mutations, or LLM calls should not execute directly inside Workflow logic. Activities are explicitly designed for these operations and can be retried when Workers crash, dependencies time out, or temporary failures occur. A durable agent Workflow might coordinate an LLM planning step, a remote tool invocation, and persistence of the final result: Java public AgentResult run(AgentRequest request) { Plan plan = activities.createPlan(request); ToolResult toolResult = activities.executeTool(plan); return activities.storeResult(request.executionKey(), toolResult); } The relevant Activity options should make failure behavior explicit rather than inheriting assumptions from the MCP request timeout. Java ActivityOptions options = ActivityOptions.newBuilder() .setStartToCloseTimeout(Duration.ofMinutes(2)) .setRetryOptions(RetryOptions.newBuilder() .setInitialInterval(Duration.ofSeconds(1)) .setBackoffCoefficient(2.0) .setMaximumInterval(Duration.ofSeconds(30)) .setMaximumAttempts(8) .build()) .build(); Temporal requires at least one Activity timeout and strongly recommends Start-To-Close for detecting Worker loss or stalled attempts. Retry backoff remains durable even when the Worker process disappears, because retry state is maintained by the Temporal Service rather than an application thread. Retries do not create exactly-once side effects. Temporal guarantees that a completed Activity is observed as completed once by the Workflow, but an Activity may execute more than once before that successful completion is recorded. A remote service could therefore receive the same write twice if the first call succeeds, but the Activity Worker crashes before reporting completion. Temporal recommends idempotent Activity implementations and specifically notes that Workflow Run ID combined with Activity ID can form an idempotency key that remains stable across retry attempts. Java String idempotencyKey = Activity.getExecutionContext().getInfo().getWorkflowRunId() + ":" + Activity.getExecutionContext().getInfo().getActivityId(); return remoteExecutor.execute(command, idempotencyKey); The receiving system should persist that key and return the original outcome when the same operation arrives again. Durable orchestration without idempotent side effects can preserve Workflow progress while still duplicating external mutations. Disconnect, Cancellation, and Result Retrieval Are Different Operations Transport cancellation requires deliberate semantics. Under modern MCP Streamable HTTP, cancellation is represented by closing the in-flight request stream. Earlier MCP revisions use notifications/cancelled for request cancellation, while the current protocol removes session coupling for normal HTTP requests. The Java SDK documentation also distinguishes request timeout from remote cancellation in older client behavior: a caller timing out does not automatically prove that server-side work has stopped. For durable agent execution, an MCP disconnect should normally mean only that the client stopped waiting. It should not automatically cancel the Temporal Workflow. Otherwise a transient Wi-Fi failure, proxy timeout, browser closure, or application restart becomes a business cancellation signal. Cancellation should instead be exposed as an explicit tool such as cancel_agent_job. That handler can target the Temporal Workflow by ID and request cancellation intentionally. Java WorkflowStub workflow = workflowClient.newUntypedWorkflowStub(workflowId); workflow.cancel(); Temporal cancellation is cooperative. A Workflow can observe cancellation and perform cleanup, while Activity cancellation requires additional care because cancellation does not forcibly interrupt arbitrary Activity code. Long-running Activities generally need heartbeats so cancellation can be delivered and progress can be checkpointed. Temporal documents that an Activity without heartbeats may continue until its timeout even after cancellation has been requested. Result retrieval should similarly be independent of the original MCP connection. A later get_agent_job call can reconstruct a Temporal stub from the Workflow ID and wait for or inspect the durable execution. Java WorkflowStub workflow = workflowClient.newUntypedWorkflowStub(workflowId); AgentResult result = workflow.getResult(AgentResult.class); WorkflowStub.getResult waits on the Temporal Service for Workflow completion, and a stub can be recreated from a known Workflow ID after the original application process or connection has disappeared. This makes the execution handle the durable rendezvous point between the MCP layer and the agent job. Security and Failure Testing Still Matter Durability does not replace authorization. A server that exposes get_agent_job or cancel_agent_job must verify that the authenticated principal is permitted to access the referenced Workflow ID. Modern MCP places authentication and authorization outside the core protocol transport and expects server implementations to enforce them at the HTTP or application boundary. The Java SDK explicitly delegates authentication and authorization to application infrastructure such as servlet filters or Spring Security. Workflow IDs therefore should not function as bearer credentials. A stored execution record should bind the Workflow ID to the authenticated tenant, account, or principal, and every retrieval or cancellation request should validate that relationship before contacting Temporal. Legacy MCP session deployments require an additional precaution because session identifiers must also be bound to authenticated identity; the Java SDK warns that session IDs alone do not provide user isolation. Fault testing should exercise failures at the boundaries that durability is expected to survive. A Worker can be terminated after an Activity completes, a dependency can return transient failures until the Retry Policy succeeds, the MCP connection can be closed immediately after Workflow start, and the result can then be retrieved through a fresh client process using the same Workflow ID. Temporal’s replay model is specifically designed so another Worker can reconstruct Workflow state from Event History and continue without re-running already recorded completed steps. Worker shutdown behavior should also be tested under realistic Activity load because abrupt termination can cause running Activity attempts to time out and retry. A fault-tolerant MCP server therefore requires more than retrying HTTP requests. Durable execution emerges when MCP request lifetime, business execution lifetime, and cancellation semantics are modeled separately. MCP provides the interoperable tool boundary; Temporal supplies persisted Workflow state, replay, Activity retries, stable execution identity, and post-disconnect result retrieval. With explicit Workflow IDs, idempotent Activities, intentional cancellation, authorization on every execution handle, and fault tests that include real process and network failures, long-running AI agent operations can continue correctly even after the connection that started them no longer exists.

By Akhil Madineni DZone Core CORE
Spec-Driven Delegation: Governing Uneven AI Coding Capacity
Spec-Driven Delegation: Governing Uneven AI Coding Capacity

AI coding capacity rarely lands evenly across a team. Copilot usually arrives through a company contract where each developer works against a personal limit per billing period: a per-user credit allowance, or a per-user budget that admins set on top of the organization's pool. Some developers burn through theirs in the first week. Others end the period with credits left over, and some have no license at all. Each limit belongs to one person, so the leftover credits do nothing for the colleague who ran out. That is capacity the company has already paid for, sitting idle next to people who could use it. The usual workaround is a favor in a chat window: "Can you run this through Copilot for me?" It works once. As a habit, it breaks down quickly. The request carries half the context, the colleague spends their own allowance asking clarifying questions, nobody reviews what was asked for, and whatever was decided lives in a Copilot conversation that nobody else will ever read. I wanted something sturdier, so I wrote it down as a process and put it in a companion repository: a PRD for the process itself, a task template, an example task (TASK-042), and the architecture, coding, and testing guides the task points to. This article is about the governance side of that proposal: who is responsible for what, where the quality gates sit, how accountability is kept, and how you would tell whether it is working. It describes a proposed process. I don't have adoption numbers from a live rollout, and I won't invent any. The Model in One Paragraph A developer who owns a piece of work but lacks AI capacity (the owner) writes a task specification as a Markdown file in the repository. A reviewer checks it against a definition of ready. A colleague with spare Copilot capacity (the delegate) implements it with Copilot, runs the tests, and writes implementation notes back into the same file. The owner validates the result, makes the final commit, and opens the pull request, which goes through the same CI/CD pipeline as everything else. One rule underpins all of it: nobody transfers tokens, credits, licenses, or accounts. The delegate uses their own seat for work assigned to them through the normal tracker, and the only thing that moves between people is a specification. Where Spec-Driven Development and Spec Kit Fit The process is spec-driven development applied to a staffing problem. In spec-driven development, a written specification comes first, and the code is generated from it, so the spec stays the reference when the code is reviewed or changed. GitHub Spec Kit packages that approach as a set of agent commands. You run /speckit-constitution once per project, then /speckit-specify, /speckit-plan, /speckit-tasks and /speckit-implement for each feature, followed by /speckit-converge. Implement and converge repeat until converge reports "Converged". Spec Kit supports Copilot directly: install the CLI with uv tool install specify-cli and run specify init <project> --integration copilot. In Spec Kit, one person drives every step. This process splits the same steps across roles, and the spec becomes the handoff between two people as well as the input to the agent: Spec Kit stepIn this processWhoConstitutionTeam standards in /docs and .github/copilot-instructions.mdTeam, maintained by tech leadsSpecifyBusiness requirements written up as a taskOwner, from the business inputPlan and tasksThe approved TASK-NNN.md fileOwner writes it, reviewer approves itImplementThe Copilot session that spends creditsDelegateConvergeThe validation loop until the result matches the specOwner, with the delegate for more iterations Teams already using Spec Kit can keep its commands and add the role split. Teams that aren't can use the plain Markdown template from the companion repo and get the same structure. Roles and Responsibilities A process that spans two people and an AI needs explicit ownership, or every failure turns into "I thought you checked that". The PRD defines four roles. The table below turns them into a RACI matrix (Responsible, Accountable, Consulted, Informed) across the steps of one task. ActivityBusinessOwnerReviewerDelegateCI/CDRequirements and acceptance criteriaR/ACIWrite TASK-NNN.md and open the issueCR/ACheck the definition of readyCR/AChoose a delegateR/ACImplement with Copilot (code, tests, docs)ARRun the full test suite before handbackARFill in implementation notesARValidate the resultCR/ACFinal commit and pull requestR/ABuild, tests, scans, quality gatesIRPromote reusable notes into /docsR/ACC Look at the Owner column. Apart from the requirements, the readiness check, and the pipeline itself, every row has an "A" there. The owner is accountable for the task from the moment it is written until it merges, including the steps the delegate performs. If accountability followed whoever held a Copilot license, it would move from person to person with each task. The owner knows the domain, wrote the spec, and will maintain the code afterward, so the owner signs off. The reviewer's role is narrow on purpose. They don't review code at this stage. They review the specification before anybody spends credits on it. Code review still happens later on the pull request, through whatever review rules the repository already enforces. Figure 1: One delegated task end to end. The readiness review happens before any AI credits are spent. Legend ColorParticipantBlueOwner, accountable for the taskPurpleReviewer, gatekeeper for the specificationGreenDelegate, the only role that spends creditsYellowCopilot in agent modeOrangeGit repository (/docs/backlog)RedCI/CD pipeline The Specification Is the Interface Treat the task file the way you would treat an API contract between two services. Each side can work without knowing the other's internals, as long as both honor the contract. Here the two sides happen to be a person and a person-plus-AI, and the contract is a Markdown file under version control. This is the core of TASK-042 from the companion repo: Markdown # TASK-042: Generate order summary report Status: Approved Owner: <name> Reviewer: <name> Delegate: <name> Issue: <link> ## Objective Generate the order summary report from normalized order records. ## Expected behavior 1. Load the report configuration. 2. Retrieve the eligible orders. 3. Generate the report. 4. Store the delivery metadata. ## Architecture constraints - Follow [ARCHITECTURE.md](../ARCHITECTURE.md). - Follow [CODING_GUIDE.md](../CODING_GUIDE.md). - Do not bypass the defined service boundaries. ## Acceptance criteria - [ ] The report is generated for all eligible orders. - [ ] The job can be restarted after a failure. - [ ] A failed run is recorded. - [ ] Unit tests cover the new code. - [ ] Integration tests cover the end-to-end flow. ## Out of scope - File transport - Customer notification ## References - [TESTING_GUIDE.md](../TESTING_GUIDE.md) - [Report generation design](../specs/report-generation/design.md) ## Implementation notes Filled in by the delegate at handback. - Changed: - Decisions: - Open questions: Each section maps to a familiar contract term: Objective and expected behavior are the operation's signature. They say what the work does, in steps that can be checked.Architecture constraints are invariants. In the example repo, ARCHITECTURE.md says a layer never calls the layer above it and services never read each other's tables. A constraint stated once in a guide and referenced from every task survives far better than one repeated in a chat prompt.Acceptance criteria are postconditions. The testing guide requires each criterion to map to at least one test, which turns the contract into something a machine can partly verify.Out of scope prevents scope creep. An AI agent with file-system access will happily "improve" adjacent code. Telling it in writing what not to touch is cheaper than reverting it later.References are the context window, made explicit. The delegate points Copilot at these files instead of pasting their content.Implementation notes are the response payload: what changed, what was decided, and what is still open. The status field (Draft, Approved, In progress, In validation, Done) gives the file a small lifecycle. Each task also gets a GitHub issue with an ai-delegation label that links the file, so the issue board shows which tasks are waiting for a delegate and who has taken which. The file holds the content and the issue handles the workflow, so the two don't compete. Definition of Ready as a Quality Gate In this model, the scarce resource is the delegate's AI allowance, plus their time. Both get wasted the same way: the agent has to guess, guesses wrong, and the delegate burns credits steering it back. An agent guesses when the spec leaves a gap, and gaps are cheapest to close before anyone starts a session. So the process puts a gate in front of the expensive step, the same way a pipeline runs cheap checks before expensive ones. The reviewer approves a task only when all of these hold: The objective fits in one or two sentences.Each expected behavior is a concrete step, not a wish.Each acceptance criterion can be checked by a test or a visible result.Out of scope is listed.Every referenced document exists and is current.Input and output examples are included where the format matters.The task contains no secrets, credentials, or production data.The task fits one session. As a rule of thumb, it should produce a PR one person can review in under an hour. Bigger work is split. None of these items requires AI capacity. The owner, who by definition is short on credits, does the parts of the job that don't consume them: thinking, specifying, and later validating. The credits go to the implementation, where an agent saves the most typing. Figure 2: Two loops. The review loop is cheap and can run as often as needed. The implementation loop consumes credits, so the first loop exists to keep the second one short. Legend ElementMeaningSwimlane colorRole performing the stepOrange diamondDecision pointUpward return arrowLoop back to an earlier step The second loop has a rule of its own. When the owner finds a gap during validation, small fixes are done directly. Anything bigger goes back into the task file first and only then to the delegate. That keeps the spec in sync with what was built, and it stops the iteration from sliding back into an untracked chat thread. Ownership and the Same Gates for Everyone Two design choices keep delegated work from becoming a second-class citizen. First, the owner validates, and the owner opens the pull request. The delegate hands back a branch with passing tests and filled-in notes and never merges it. The owner runs the unit and integration tests, any functional or simulation tests, and checks the affected screens. Then the owner makes the final commit. When a production issue shows up six months later, the PR history points to someone who understood the change well enough to sign for it. Second, there is no AI lane in the pipeline. Delegated work passes the same build, tests, security scans, and quality gates as anything else, and merges only if all of them pass. It can be tempting to relax review for "simple generated code." The PRD rules that out as a non-goal: the process must not change existing CI/CD, review, or quality-gate rules. Gates that are adequate for human-written code should hold for agent-written code too. If they don't, they had gaps before any agent showed up. A variant works with the same governance. Copilot cloud agent (which GitHub's documentation earlier called the coding agent) can start work from a GitHub issue, work in the background in its own environment, and open a pull request. A delegate can start that session from the task's issue. The owner then validates the agent's PR exactly as they would validate a branch from a colleague. GitHub's own docs say the session logs "do not replace your own review and testing", which matches the model. Knowledge Retention: /docs versus Chat History The informal favor also loses knowledge. Every clarifying exchange, every rejected approach, and every assumption the agent made lives in a session that ends. The model counters this with a simple rule from the PRD: the repository is the source of truth, and nothing needed to understand a task exists only in a Copilot conversation. In practice, that rule rests on three layers of version-controlled artifacts. Figure 3: Repository artifacts that carry the process. Standing docs change slowly, task files change per unit of work, and the .github configuration shapes how the AI behaves for every delegate. Legend ColorArtifact typeLight blueStanding documentation (/docs, /docs/specs)AmberTask specification (/docs/backlog)GreenCopilot configuration (.github)RedQuality gate (CI workflow)PurpleTracking (GitHub issue) The .github layer keeps delegates consistent. Without it, every delegate brings their own habits and prompts, and the output varies with whoever picks up the task. GitHub documents a repository-wide instructions file at .github/copilot-instructions.md, path-specific instructions in .github/instructions/NAME.instructions.md (each with an applyTo glob), and AGENTS.md files that agents read. Reusable prompt files live in .github/prompts with a .prompt.md extension and are available in VS Code, Visual Studio and JetBrains IDEs. The companion repo ships both files. The repository instructions tell Copilot that the task file is the only source of requirements: Markdown ## When implementing a task - The task file in `docs/backlog/TASK-NNN-*.md` is the only source of requirements. Do not add behavior it does not ask for, and respect its "Out of scope" list. - Follow `docs/ARCHITECTURE.md`, `docs/CODING_GUIDE.md` and `docs/TESTING_GUIDE.md`. - Every acceptance criterion maps to at least one test. Run the full test suite before handing back. - Fill in the task's "Implementation notes" section: what changed, decisions made, open questions. - If the task is ambiguous, stop and list the questions instead of guessing. The shared implement-task prompt gives every delegate the same procedure, so nobody re-explains the conventions, and every handback looks the same: YAML --- description: Implement an approved TASK-NNN.md spec as a delegate, then hand it back to the owner agent: agent --- You are the delegate for the task file given in the input (for example `#file:docs/backlog/TASK-042-order-summary-report.md`). 1. Read the task file and every document in its "References" and "Architecture constraints" sections. 2. Check the task against the definition of ready in `docs/spec/PRD-copilot-capacity-sharing.md`. If anything is missing or ambiguous, stop and list the questions for the owner. Do not implement. 3. Propose a short plan: files to create or change, and which test covers each acceptance criterion. Wait for confirmation. 4. Implement the plan: code, unit tests, integration tests and documentation updates. Stay inside the task's scope. 5. Run the full test suite. Fix failures, including existing tests you broke. 6. Fill in the task's "Implementation notes" (Changed, Decisions, Open questions) and set its status to "In validation". 7. Summarize the result for the owner in five lines or fewer. In step 2, the prompt re-checks the definition of ready before writing any code, so a spec that slipped past the reviewer gets stopped at the cost of one short exchange instead of a full implementation. Step 3 makes "plan first" part of the procedure instead of leaving it to each delegate's discipline. The last step of the process closes the loop on knowledge: after merge, the team moves anything worth reusing from the implementation notes into /docs. A decision about restart semantics, for example, belongs in specs/report-generation/design.md, where the next task can reference it. Spending Credits Deliberately GitHub changed how Copilot usage is metered during 2026. Since June 1, 2026, plans are billed by usage: GitHub AI Credits, consumed according to token usage, replaced premium requests as the billing unit (premium requests survive only on some legacy plans), and code completions are not billed in credits. Plan details and allowances keep moving, so I won't quote them here. Check the Copilot billing docs for your plan. From the organization's point of view, the credits form one budget, but per-user allowances or per-user budgets split it into personal limits. The process doesn't change whose limit is whose. It changes where the work goes, so a developer with room left can serve a colleague who has hit their limit, without buying extra seats. Where an organization pools credits with no per-user caps, that argument is weaker, but developers without a license still need this route. Whatever the unit, the process treats credits as a budget and shapes sessions to match: Run one task per session, started fresh. Long sessions drag old context along, and token-based billing charges for it.Reference files instead of pasting them. Point Copilot at the task file and its references (#file, #codebase in VS Code chat) rather than copying content into the prompt.Plan before editing. The shared prompt stops after the plan. A wrong plan caught early costs one exchange. A wrong implementation costs many.Match the model to the step. Routine steps (boilerplate, renames, simple tests) rarely need the most expensive model. Check current model rates before choosing, since they change.Stop loops early. If the agent keeps circling, the spec is the problem. Fix the task file instead of retrying. The same habits help owners stretch their own small allowance. Security and Policy Delegation doesn't widen anyone's access. The delegate already has repository access through the normal permissions, and the process grants nothing new. Three rules keep it that way: Task files never contain secrets, credentials, or production data. Use synthetic examples. Task files are committed and readable by everyone with repo access, and they are fed to an AI tool.Copilot is used only within the organization's approved AI policy and settings, such as content exclusions and public code filtering.Work the delegate's role could not normally touch stays with the owner. "Needs access the delegate lacks" is one of the explicit reasons not to delegate. There is one question I would put to the organization's licensing or legal contact before rollout, not answer myself: does having one seat holder implement work owned by a colleague fit your agreement and internal policy? Structurally, the delegate is just working an assigned ticket with their own tool, which is ordinary teamwork. Still, a short written confirmation is cheaper than an awkward conversation later. Measuring Whether It Pays Off A process without signals turns into ritual. The PRD proposes a small set of per-sprint measures. None of them needs new tooling, and each one answers a specific question. SignalQuestion it answersWarning signTasks delegated and mergedIs the process being used at all?Many delegated, few mergedIterations per taskWas the spec actually ready?More than two iterations on a regular basisTime from approval to merge vs. similar hand-built tasksDoes delegation save time end to end?Delegated tasks consistently slowerTasks waiting for a delegateIs capacity matched to demand?Queue growing sprint over sprintCredits left unused at period endIs paid capacity reaching real work?Delegates finish periods with large balances while tasks waitCredits consumed per delegated taskAre sessions efficient?High spend on tasks that needed many iterations Most of this comes straight from GitHub. For example, approval-to-merge time can be approximated from the ai-delegation issues: Shell # Closed delegation issues with lead time in days (issue creation as a proxy for approval) gh issue list --label ai-delegation --state closed --limit 200 \ --json number,title,createdAt,closedAt | jq -r '.[] | [.number, (((.closedAt|fromdateiso8601) - (.createdAt|fromdateiso8601)) / 86400 | floor), .title] | @tsv' For the credit signal, GitHub added a per-user ai_credits_used field to the Copilot usage metrics API in June 2026. GitHub describes it as a metrics signal rather than a billed total, which is precise enough for spotting trends. Comparing a delegate's consumption in sprints with and without delegated tasks gives a rough cost per task. Watch the iteration count most closely. It measures spec quality, which is the one variable the owner fully controls. If it creeps up, tighten the definition of ready before anything else. Trade-Offs and When Not to Delegate Delegation has a fixed overhead: a spec, a review, a handoff, and a validation. That overhead is worth paying only when the implementation is larger than the ceremony around it. Figure 4: A quick screen before writing a task file. Legend ColorMeaningOrange diamondScreening questionBlue boxKeep the work with the ownerGrey boxNeutral stepGreen boxDelegate through a task file Good candidates are new endpoints, services, or jobs with a clear spec, test suites for existing code, mechanical refactors across many files, boilerplate (DTOs, mappers, repositories, migrations), and documentation generated from code. Poor candidates are one-line fixes, exploratory work where the design is still open, live incidents, and anything that needs access the delegate doesn't have. The process also has costs: Latency: a task waits for review and then for a delegate. For urgent work, this is a real cost, which is why incidents are excluded.Reviewer bottleneck: if one tech lead reviews every spec, they become the constraint. Rotate the reviewer role or let senior developers review each other's specs.Uneven load on delegates: the people with spare capacity can end up as an internal service desk. The capacity notes on the issue board ("can take two tasks this sprint") exist, so delegates control their own intake.Skill drift: an owner who never drives an AI agent doesn't learn to. If the gap in capacity is temporary, plan to close it rather than institutionalize it.Specs that rot: a task file is only as good as the documents it references. If ARCHITECTURE.md is stale, every task that points to it inherits the error. The readiness check on referenced docs is there for that reason. A side effect may outlast the whole arrangement: teams that adopt it end up with better specs and better standing documentation, whether or not anyone is short on credits. If capacity evens out next year, the team keeps the specs and the /docs folder. Summary Uneven AI capacity is a resource-allocation problem: credits the company already paid for sit unused next to developers who have none. Informal favors handle it poorly. A version-controlled task spec handles it as a contract.Nobody transfers credits or accounts. The owner specifies and validates, and the delegate spends credits only on implementation.The definition of ready is a quality gate placed before the expensive step, so gaps in the spec are closed before anyone spends credits on them.The owner stays accountable end to end and opens the PR. Delegated work passes exactly the same CI/CD gates as any other change.Knowledge lives in /docs and .github, not in chat sessions, and a small set of signals tells you whether the process earns its overhead. The full PRD, the task template, TASK-042 and the supporting guides are in the companion repo. Fork it and adapt the roles and the definition of "ready" to your own team. How does your team handle uneven access to AI coding tools? I'm curious whether others formalized it or still run on favors. Please let me know in the comments. Examples repository: every example in this article (the PRD, the TASK-042 task spec, the team guides, the Copilot instructions, the prompt file, and the diagrams) is in https://github.com/wallaceespindola/share-tokens-using-spec-driven-dev. Need more tech insights? Check out my GitHub, LinkedIn, and Speaker Deck. Happy coding! Wallace Espindola, Solution Architect GitHub: https://github.com/wallaceespindola/LinkedIn: https://www.linkedin.com/in/wallaceespindola/Speaker Deck: https://speakerdeck.com/wallacese

By Wallace Espindola

Culture and Methodologies

Agile

Career Development

Methodologies

Team Management

Data Integration vs Workflow Orchestration

December 4, 2026 by Kai Wähner DZone Core CORE

Staff Engineers in the Age of AI: Rethinking Technical Leadership

December 2, 2026 by Otavio Santana DZone Core CORE

Seven AI Adoption Failures and How to Overcome Them

December 1, 2026 by Stefan Wolpers DZone Core CORE

Data Engineering

AI/ML

Big Data

Databases

IoT

Serverless or Always-On GPUs? The Break-Even Math for LLM Inference

December 4, 2026 by Matt Sarrel

Content Negotiation for AI Agents: Serving Markdown Beside Your HTML

December 4, 2026 by Prajwal Hallale

Post-Migration Modernization: When and How to Refactor

December 4, 2026 by Srinivasarao Thumala

Software Design and Architecture

Cloud Architecture

Integration

Microservices

Performance

Data Integration vs Workflow Orchestration

December 4, 2026 by Kai Wähner DZone Core CORE

Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy

December 4, 2026 by Stelios Manioudakis DZone Core CORE

Seven Failure Modes Every HTTP Client Should Handle: Lessons From Fixing 31 Bugs

December 3, 2026 by Mohammad Garmabi

Coding

Frameworks

Java

JavaScript

Languages

Tools

Content Negotiation for AI Agents: Serving Markdown Beside Your HTML

December 4, 2026 by Prajwal Hallale

Python Shared Memory: Resource Trackers, Process Lifetime, and Premature Cleanup

December 4, 2026 by Sagar Bonthu

Checkpoints for Long MCP Requests: Only the User's Click Approves

December 4, 2026 by Ilia Kuzmin

Testing, Deployment, and Maintenance

Deployment

DevOps and CI/CD

Maintenance

Monitoring and Observability

Serverless or Always-On GPUs? The Break-Even Math for LLM Inference

December 4, 2026 by Matt Sarrel

Data Integration vs Workflow Orchestration

December 4, 2026 by Kai Wähner DZone Core CORE

Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy

December 4, 2026 by Stelios Manioudakis DZone Core CORE

Popular

AI/ML

Java

JavaScript

Open Source

Serverless or Always-On GPUs? The Break-Even Math for LLM Inference

December 4, 2026 by Matt Sarrel

Content Negotiation for AI Agents: Serving Markdown Beside Your HTML

December 4, 2026 by Prajwal Hallale

Keeping AI Code Generation Honest: A Deterministic Control Plane for Multi-Agent LLM Workflows

December 4, 2026 by Janani Annur Thiruvengadam DZone Core CORE

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×