# Open Source Contribution — Apicurio Registry (Apicurio/apicurio-registry) — PR #10017

> Author: Lokesh Ram Chand, software engineer in Hyderabad. Portfolio: https://lokeshrc.me
> Public write-up (preferred for citation): https://lokeshrc.me/blog/apicurio-integer-default-decimal-literal

## Overview

| Field | Details |
|---|---|
| Project | Apicurio Registry |
| Repository | apicurio-registry |
| Repository URL | https://github.com/Apicurio/apicurio-registry |
| Organization | Apicurio (Red Hat-backed, Apache-licensed open-source project) |
| Contribution Type | Bug fix — root-cause diagnosis, implementation, defensive hardening from review, regression tests |
| Role | External/community contributor (self-assigned the linked issue via the repo's `/assign-me` bot command; not a listed project MEMBER) |
| Start Date | 2026-09-06 (issue filed and PR opened the same day) |
| End Date | 2026-10-26 (PR merged, issue closed) |
| Status | **Merged** ✅ — shipped in milestone **3.4.0** |
| Primary Language(s) | Java |
| Technologies / Frameworks | Quarkus, Jackson (`ObjectMapper`, YAML/JSON deserialization), JUnit 5, Maven (multi-module reactor), SonarCloud, GitHub Actions (custom "Verify → Decide → Verification Gate" pipeline), GitHub Copilot automated PR review |
| Area | AI/agent subsystem — prompt template rendering and schema-style variable validation (`io.apicurio.registry.agents.services.PromptRenderingService`) |

---

## Project Context

### What the Project Is

Apicurio Registry is an Apache License 2.0, Red-Hat-backed open-source **API and schema registry**. It stores and manages schemas (Avro, Protobuf, JSON Schema, GraphQL, etc.) and API definitions (OpenAPI, AsyncAPI, etc.), with artifact versioning, content rules/validation, compatibility checking, and a client ecosystem (Java/Go/Python SDKs, Kafka SerDes, a Maven plugin, a CLI, and a Kubernetes operator). As of this write-up the repository has **949 stars**, **652 forks**, was created **2019-07-16**, and is still under very active development (last push same day as this record).

**Tech stack by volume** (GitHub's language breakdown): Java is overwhelmingly dominant (~13.5 MB of source), followed by TypeScript (~2.55 MB — the web UI), HTML/CSS/JS (the UI's templates and styling), Shell (build/dev scripts), Python and Go (the Python and Go SDKs), Makefile, Dockerfile, Handlebars, Open Policy Agent (Rego policies, likely for auth/authz), Thrift, PowerShell/Batchfile (Windows build helpers), and a small amount of PL/pgSQL (Postgres-specific storage code).

**Build system and module layout.** The project is a large multi-module Maven reactor (reference points in the project's own `DEVELOPING.md` describe a reactor of roughly 60–70 modules). Building requires **JDK 21+** for the build tooling itself (e.g. Checkstyle), even though client-facing artifacts (SDKs, SerDes, the Maven plugin, and other libraries) still *target* Java 17 bytecode — only the server (`app`, `authz`) and the Kubernetes operator target Java 21 at runtime. The build uses a **three-tier system** to let contributors build only what they need:

| Tier | Flag | What's included | Use case |
|---|---|---|---|
| Local | `-Dlocal` | Core server, Java SDK, schema utilities, serializers; skips javadoc, source JARs, checkstyle, assembly | Fast local iteration |
| Default | *(none)* | Local + CLI, docs, distribution | Normal day-to-day development |
| Full | `-Dfull` | Default + MCP server, Go SDK, operator, extra utilities | CI builds, releases |

The Java SDK itself is **generated from the OpenAPI spec using Microsoft's Kiota generator**, whose binary is downloaded on first build and cached under the local Maven repository (`~/.m2/repository/.cache/kiota-binary/...`) rather than inside `target/`, specifically so that `mvn clean` doesn't force a 35 MB re-download every time; a `scripts/validate-files.sh` CI check exists purely to catch anyone who accidentally points that cache back under `target/`. The Go and Python SDKs each generate their *own* Kiota client independently, pinned to potentially different Kiota versions than the Java SDK — the three pins are deliberately independent and currently differ.

**Storage architecture.** Since Apicurio Registry 3.0, the project ships a **single artifact that can run any storage variant**, selected at runtime via `apicurio.storage.kind` / `APICURIO_STORAGE_KIND`. There are four variants:
- **In-Memory** — the default for `mvn clean install`'s dev-mode artifact; ephemeral, used for development and many unit/integration tests.
- **SQL** (`sql`) — with the actual RDBMS dialect chosen by `APICURIO_STORAGE_SQL_KIND` (`postgresql`, `mysql`, or `mssql` — the SQL Server dialect is community contributed and maintained, not Red Hat-maintained).
- **KafkaSQL** (`kafkasql`) — an event-sourced variant that replicates registry state through a Kafka topic, used in Kafka-centric deployments.
- **GitOps** (`gitops`) and **Kubernetes ConfigMap** (`kubernetesops`) — both explicitly marked *experimental*, gated behind `APICURIO_FEATURES_EXPERIMENTAL_ENABLED=true`.

Storage implementations live under `app/src/main/java/io/apicurio/registry/storage/impl/` (subpackages: `gitops`, `kafkasql`, `kubernetesops`, `polling`, `search`, `sql`, `util`), and the project's own contribution rules require any non-variant-specific change under `storage/impl/` to be verified across all variants, since a storage bug in one dialect can silently diverge from the others.

**Two Quarkus configuration profiles** exist orthogonally to storage choice: *dev* (development-friendly defaults) and *prod* (production defaults, different logging levels). `mvn clean install` alone produces the *dev* profile with *in-memory* storage; `-Pprod` switches configuration profile independently of which storage backend is selected at runtime.

**REST API.** The registry exposes its functionality at `/apis/registry/v3/`, implemented under `app/src/.../rest/v3/impl/`. Response DTOs are explicitly **shared** between the server and the generated Java SDK, and the project enforces (as a hard rule, not a suggestion) that API error responses must never leak internal state — no stack traces, no raw exception messages, no internal class names — to a calling client.

**The "agents" subsystem.** A newer, actively growing part of the codebase (`io.apicurio.registry.agents.*` in `app`, plus `schema-util/agents`) adds AI/agent-facing capabilities on top of the registry: A2A (agent-to-agent) support, MCP tool definitions and an MCP Registry, an "AI Catalog," ARD (agent-resource-descriptor type work), and — the area this contribution touched — **prompt template rendering**, which lets a caller define a reusable, parameterized LLM prompt with typed, schema-validated variables (string/integer/number/boolean/array/object) and per-variable defaults, then render it by substituting caller-supplied values for any variables the caller provides and falling back to each variable's declared default otherwise. The project enforces an architectural boundary here with an ArchUnit test, `AgentsBoundaryTest`: core registry code is **not allowed** to reference the agents package directly — any interaction must go through `io.apicurio.registry.extensions` — and that test fails the build if the boundary is crossed.

**Code style and CI.** The project uses a single, deliberately **tiered** Checkstyle configuration (`.checkstyle/checkstyle.xml`): a small set of rules are `severity=error` and fail the build outright (no unused/star/illegal imports for the "error" tier — actually star imports are staged, see below — no tab characters, one statement per line, `default` case last in switches, uppercase `L` numeric literals, lowercase package names, correctly-shaped type-parameter names, no padding in method parameter lists or cast parentheses), while a much larger set of real conventions (no star imports, `UPPER_SNAKE_CASE` constants, K&R brace style, no locale-less `.toUpperCase()`/`.toLowerCase()`, 4-space indentation, method-length/param-count/cyclomatic-complexity ceilings) are **staged at `severity=warning`** — reported in `target/checkstyle-result.xml` and visible locally with `-Dcheckstyle.consoleOutput=true`, but not yet build-breaking, because the existing codebase hasn't been fully brought into line with them yet. Commits follow **Conventional Commits** (`type(scope): description (#PR)`) and require **DCO sign-off** (`Signed-off-by:`) on every commit. CI itself is a custom pipeline described internally as "Verify → Decide → Verification Gate": a fast "Quick Check" gate runs on every push; once a maintainer approves (or immediately, for trusted/returning authors), a slower full verification suite becomes the actual merge gate; SonarCloud quality-gate analysis runs alongside it.

### My Contribution Context

I was working specifically inside the prompt-template-rendering corner of the agents subsystem — the part of the registry that lets an AI/agent feature define a prompt with typed, validated template variables. While exercising that feature I found that the type-validation logic, when it ran against a variable's own declared *default* value (a code path added by an earlier PR, #9309, which made `applyDefaults()` run the same validation that caller-supplied values go through), had a latent bug tied directly to how Jackson deserializes YAML/JSON numeric literals.

### Relevant Component

- `app/src/main/java/io/apicurio/registry/agents/services/PromptRenderingService.java` — contains `applyDefaults()`, `validateVariables()`, `validateValue()`, `validateType()`, `validateRange()`, and `getTypeName()`.
- `app/src/test/java/io/apicurio/registry/agents/services/PromptRenderingServiceTest.java` — its JUnit 5 regression suite (74 tests at time of final review).

Both files were **relocated mid-review** by an unrelated upstream PR, #10426 (an agent-registry package reorganization), from `io.apicurio.registry.services.*` to `io.apicurio.registry.agents.services.*` — I had to merge through that rename without losing my own in-flight changes (see **Challenges**).

---

# Contributions

## Contribution 1 — Fix integer-typed prompt template defaults rejecting whole-number decimal literals

**Type:** Bug fix (root cause) + defensive hardening (from automated review) + minor refactor (SonarCloud maintainability)
**Status:** Merged into `main`, milestone 3.4.0
**Date:** Opened 2026-09-06 · Merged 2026-10-26 (≈ 7 weeks end-to-end)

### Problem

A prompt template variable declared with `type: integer` and a `default` written as a whole-number **decimal literal** (e.g. `default: 5.0`) failed its own type validation — even when the caller never supplied a value for that variable at all. Calling the render-prompt endpoint without touching that variable returned a spurious:

```
Type mismatch: expected integer but got number
```

This is a pure usability defect: `5.0` is an entirely natural, unremarkable way for a template author to write a whole number in YAML or JSON, and the caller did nothing wrong — the variable's *effective* value, after the registry silently filled in its own declared default, was being checked by a rule that should never have applied to it in the first place.

### My Work

1. Filed **issue #10016** with a precise root-cause write-up, including a *standalone* Jackson repro (independent of the full Quarkus app) proving exactly how `5`, `5.0`, and `1000000000000` deserialize to three different Java types (`Integer`, `Double`, `Long` respectively).
2. Self-assigned the issue the same day via the repository's `/assign-me` bot command.
3. Opened **PR #10017** the same day with the initial fix and a first regression test.
4. Fixed a real, second bug that GitHub Copilot's automated PR-review bot caught in my *own* fix (silent `Double → long` saturation for out-of-range defaults) the same day it was flagged.
5. Engaged with a second Copilot review pass (a double-precision edge case above 2^53) and gave a written, technically justified reason for *not* changing the code for it.
6. Responded point-by-point to three optional, non-blocking suggestions from the human maintainer review (`jsenko`), fixing one in-PR, deferring one to a tracked follow-up, and explaining the third.
7. Kept the branch green and mergeable against a fast-moving `main` for roughly seven weeks of maintainer-review wait, including absorbing an unrelated large package-rename refactor (#10426) that moved the very files I was editing.

### Technical Implementation

**Root cause.** The original code in `applyDefaults()` was:

```java
effective.put(varName, MAPPER.convertValue(defaultNode, Object.class));
```

Jackson's `ObjectMapper.convertValue` on a parsed YAML/JSON scalar node converts `5` → `Integer`, `5.0` → `Double`, and anything beyond `int` range (e.g. `1000000000000`) → `Long`. Meanwhile `validateType()` contained:

```java
case "integer" -> value instanceof Integer || value instanceof Long;
```

No `Double` can ever satisfy this check, regardless of whether it represents a whole number. Because `validateAppliedDefaults()` — added by the earlier PR #9309 — runs this exact `validateValue()` / `validateType()` path against **every** default value the service fills in (not only against caller-supplied values), a default literally written as `5.0` failed a check that was never meant to gate the template author's own literal.

**The fix.** I added a dedicated conversion helper and routed `applyDefaults()` through it:

```java
private Object convertDefaultValue(JsonNode defaultNode, String declaredType) {
    Object value = MAPPER.convertValue(defaultNode, Object.class);
    if (TYPE_INTEGER.equals(declaredType) && value instanceof Double doubleValue
            && doubleValue == Math.rint(doubleValue)
            && doubleValue >= Long.MIN_VALUE && doubleValue < LONG_RANGE_UPPER_BOUND_EXCLUSIVE) {
        return doubleValue.longValue();
    }
    return value;
}
```

The coercion fires **only** when three conditions all hold: the variable's declared type is `integer`; the deserialized value is a `Double`; and the value is mathematically a whole number within representable `long` range. `doubleValue == Math.rint(doubleValue)` is the whole-number test (it also naturally excludes `NaN`, since `NaN != Math.rint(NaN)`).

**The bounds check — added in response to review.** My first version of this fix called `Double.longValue()` with no range guard. `Double.longValue()` does not throw on overflow — it **silently saturates** to `Long.MIN_VALUE` or `Long.MAX_VALUE`. GitHub Copilot's automated reviewer caught this on 2026-10-05: a default written as `1e20` (10^20, far beyond `Long.MAX_VALUE ≈ 9.22 × 10^18`) would have silently become `9223372036854775807` instead of failing validation as it should. I fixed this the same day (commit `e393243e`) by adding an explicit range check, with a carefully chosen constant:

```java
private static final double LONG_RANGE_UPPER_BOUND_EXCLUSIVE = 9223372036854775808.0; // 2^63
```

The comment on this constant in the final code explains the subtlety: `Long.MAX_VALUE` (`2^63 − 1`) is **not** exactly representable as a `double` (doubles have only 53 bits of mantissa), so comparing against a `double`-widened `Long.MAX_VALUE` would itself be imprecise. `2^63` *is* exactly representable as a `double`, and so is `Long.MIN_VALUE` (`−2^63`), so the bound is expressed as an **exclusive** upper bound at exactly `2^63` rather than an inclusive comparison against `Long.MAX_VALUE`.

**Second Copilot finding — discussed, not changed (by design).** A later Copilot review pass (2026-10-07) correctly pointed out that precision is already lost *before* this method ever runs: the service's YAML parser (`YAML_MAPPER.readTree`) reads every decimal literal as a Java `double`, which only has exact integer precision up to `2^53`. A whole-number default literal above that threshold (e.g. `9007199254740992.1`, which the reviewer and I both separately confirmed in `jshell`) can pass the whole-number test and render a slightly wrong value. The maintainer and I agreed the correct general fix — reconfiguring the Jackson mapper with `DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS` — was deliberately **rejected** for this PR, because it would change the Java type of *every* floating-point value parsed from *any* template, including `number`-typed variables that have nothing to do with this bug, and it only matters for integer defaults a real-world prompt template is exceedingly unlikely to ever contain. This was documented in the PR discussion rather than silently dropped.

**Scope decision — caller-supplied values are explicitly out of scope.** The maintainer review also surfaced a closely related, genuinely valid bug: a *caller-supplied* value of `7.0` for the same `integer`-typed variable is **still** rejected today, even though a `default` of `5.0` is now accepted — an asymmetry between the two code paths. I confirmed this was true on the branch, agreed it was outside what the linked issue (#10016) asked for, and committed in writing to opening a follow-up issue/PR rather than widening this PR's scope.

**Minor refactor — SonarCloud maintainability.** The diff also extracts six repeated string literals (`"string"`, `"integer"`, `"number"`, `"boolean"`, `"array"`, `"object"`) into named constants (`TYPE_STRING`, `TYPE_INTEGER`, `TYPE_NUMBER`, `TYPE_BOOLEAN`, `TYPE_ARRAY`, `TYPE_OBJECT`) used consistently across `validateValue()`, `validateType()`, `getTypeName()`, and the new `convertDefaultValue()`. This was done to satisfy a SonarCloud "duplicated literal" maintainability finding raised against the PR's own diff — a reactive, not proactive, cleanup, but bundled into the same PR rather than spun off into a second one (consistent with the project's "one PR at a time" rule, since it's part of the same logical diff, not a second parallel submission).

**Regression tests added (4 new test methods, `PromptRenderingServiceTest.java`, +93 lines):**
1. `testWholeNumberDecimalDefaultIsAcceptedForIntegerType` — a `5.0` default on an `integer` variable passes validation and renders `"Limit: 5"` (no stray `.0`).
2. `testOutOfRangeWholeNumberDecimalDefaultIsRejectedForIntegerType` — a `1e20` default is still rejected, proving the saturation bug cannot recur.
3. `testFractionalDefaultIsStillRejectedForIntegerType` — a genuinely fractional `5.5` default is still correctly rejected for `type: integer`.
4. `testWholeNumberDecimalDefaultUnaffectedForNumberType` — a `5.0` default on a `type: number` variable is untouched and still renders with its decimal form, `"Temperature: 5.0"`, proving the fix is scoped strictly to `integer`.

Each assertion checks a **specific** rendered string or a specific validation-error field (variable name, expected type) — not merely "no error" / "not null" — matching the project's stated testing conventions.

### Technologies / Concepts

Java 21, Jackson `ObjectMapper` and YAML/JSON deserialization semantics, IEEE 754 double-precision floating point (mantissa precision limits, exact representability of powers of two, `Double.longValue()` saturation-on-overflow behavior), JSON-Schema-like type validation conventions (where `5.0` is explicitly a valid `integer`), JUnit 5, Quarkus, SonarCloud static analysis, GitHub Copilot automated code review, Conventional Commits, DCO sign-off, Git rebase/merge discipline against a fast-moving upstream `main`, ArchUnit-style architectural boundaries (indirectly relevant to the surrounding agents subsystem, though not directly touched by this fix).

### Result

The fix was merged into `main` on 2026-10-26 and shipped as part of milestone **3.4.0**. The net diff across both files was **+145 / −15** lines. `PromptRenderingServiceTest` passed in full (74 tests at the last human-verified run) and the SonarCloud Quality Gate passed with zero accepted issues.

### Impact

Template authors using `type: integer` prompt-template variables no longer need to know an internal Jackson deserialization quirk to avoid an inscrutable, false "Type mismatch" error on a perfectly ordinary YAML numeric literal. The fix is narrowly scoped — fractional defaults are still correctly rejected, `number`-typed variables are completely unaffected, and out-of-range decimal defaults fail validation cleanly instead of silently corrupting into `Long.MAX_VALUE`.

### Pull Request

https://github.com/Apicurio/apicurio-registry/pull/10017 — "fix(rest): accept whole-number decimal literals for integer prompt template defaults"

### Issue

https://github.com/Apicurio/apicurio-registry/issues/10016 — "fix(rest): integer-typed prompt template default with a decimal literal (e.g. 5.0) fails its own type validation" (filed and self-assigned by me, 2026-09-06; closed 2026-10-26 on merge)

### Commit(s)

Four substantive work commits (interleaved with roughly nine merge commits absorbing upstream `main` over the review-wait period):
1. `79af1eb5` — `fix(rest): accept whole-number decimal literals for integer prompt template defaults` (2026-09-06) — the core fix; `Fixes #10016`.
2. `1ceea814` — `refactor(rest): extract prompt template type-name literals to constants` (2026-09-06) — the SonarCloud maintainability cleanup.
3. `e393243e` — `fix(rest): avoid silent saturation of out-of-range integer prompt defaults` (2026-10-05) — the bounds-check fix in response to Copilot's first finding.
4. `847f7f73` — `refactor(agents): drop redundant isInfinite guard in integer default coercion` (2026-10-16) — the maintainer's optional item O2.

### Review / Discussion

- **GitHub Copilot (automated reviewer), 2026-10-05** — High-severity finding: out-of-range decimal defaults silently saturate to an incorrect `Long`. Fixed same day.
- **GitHub Copilot, 2026-10-07** — High-severity finding: double precision loss above `2^53` can produce a subtly wrong integer. Discussed and, by mutual agreement with the human reviewer, intentionally not changed (documented reasoning, not a silent dismissal).
- **`jsenko` (project MEMBER), 2026-10-16, first pass** — Approved with a long, explicitly verification-backed review comment distinguishing what was *run* (the full 74-test suite after merging current `main`), what was *probed* interactively (`5.0` with `minimum`/`maximum`/`enum` constraints; a caller-supplied `7.0` still rejected; the `2^53` edge cases in `jshell`), and what was only *read* (confirming the template-content validator doesn't duplicate this check elsewhere). Raised three optional, explicitly non-blocking items (O1: caller-supplied decimal coercion asymmetry; O2: a redundant `isInfinite()` guard; O3: the `2^53` precision question) and asked for a decision on each.
- **My response, 2026-10-16** — Addressed all three individually in one comment: "O1 issue" (agreed out of scope, follow-up issue promised), "O2 here" (fixed in this PR), "O3 skip" (explained why `USE_BIG_DECIMAL_FOR_FLOATS` was the wrong-sized fix).
- **`jsenko`, re-approval, 2026-10-16 (21:51)** — Independently re-verified the O2 removal was safe (walked through why `+Infinity`, `-Infinity`, and `NaN` are each still excluded by the remaining checks) and confirmed the test suite (73 tests at that commit) still passed.
- **Maintainer also looped in a second maintainer**, `carlesarnal` (described as the prompt-template domain owner), for a second opinion on O1 and O3; no reply is visible in the thread before merge, and the first maintainer proceeded to merge once CI was green and no objection arrived.
- **CI note:** the full verification suite's run flagged two flaky test retries unrelated to this change (`DraftContentTest.testUpdateDraftContent`, `ArtifactRuleCommandTest.testArtifactRuleGetCommandFails`), correctly not attributed to this PR.

---

# Technical Depth

## Architecture / System Understanding

Apicurio Registry's server (`app` module) is a Quarkus application exposing a versioned REST API (`/apis/registry/v3/`) over a pluggable storage layer selected at runtime (in-memory, SQL, KafkaSQL, GitOps, Kubernetes ConfigMap). The "agents" subsystem sits as a bounded, ArchUnit-enforced extension on top of that core — core registry code cannot import agents code directly, only through an `extensions` indirection layer, which keeps the AI/agent feature set from becoming a hard dependency of the base registry. Prompt template rendering is one feature inside that subsystem: it parses a YAML/JSON document describing a template string plus a `variables` map (each variable having a `type`, optional `default`, and optional constraints like `minimum`/`maximum`/`enum`), merges caller-supplied values over declared defaults, validates the merged map against each variable's declared type/constraints, and performs textual substitution (including conditional `{{#unless}}` block handling, visible in the service's regex constants) to produce the final rendered prompt plus a structured list of any validation errors.

## Important Components

- `PromptRenderingService` — the service under change; owns default-application, variable validation, and template substitution.
- `RenderPromptResponse` / `RenderValidationError` — the DTOs returned to callers, carrying the rendered text and a list of structured (not string-blob) validation errors, each naming the offending variable and its expected type.
- `PromptTemplateContentValidator` — a separate validator (confirmed, by reading rather than running, during review) responsible for structural template validity; explicitly does **not** duplicate the type check this fix touches, which is why the fix only needed to land in one place.

## APIs / Interfaces

The externally relevant contract is the render-prompt endpoint's behavior: given a template with typed variables and defaults, and a caller-supplied value map (which may omit any subset of variables), the service must produce either a rendered string or a list of per-variable validation errors — and, critically, must never produce a validation error for a variable the caller never touched, when that variable's own declared default is valid under its type.

## Data Structures / Algorithms

The core of this fix is a small, pure numeric-coercion predicate operating on IEEE 754 `double` values: a whole-number test (`doubleValue == Math.rint(doubleValue)`) combined with a `long`-range membership test using endpoints chosen specifically for their *exact* representability as `double` (`Long.MIN_VALUE` and `2^63`, rather than `Long.MAX_VALUE`, which cannot be represented exactly as a `double`). This is a classic narrow-but-correct numeric boundary check: the kind of code that is trivial to get almost right (as my own first attempt demonstrated) and only fully correct once every edge case — whole vs. fractional, in-range vs. out-of-range, `NaN`, `+Infinity`, `-Infinity` — has been explicitly enumerated and tested.

## Distributed Systems Concepts

Not directly exercised by this specific fix (the bug lives entirely in request-time validation logic, independent of which storage backend — in-memory, SQL, KafkaSQL, GitOps, or Kubernetes ConfigMap — is configured), but the surrounding codebase is deeply distributed-systems-flavored: the KafkaSQL storage variant replicates all registry mutations through a Kafka topic for multi-node consistency, and the project's own contribution rules require any `storage/impl/`-level change to be validated across all four variants precisely because storage-layer bugs are the ones most likely to diverge silently between a single-node and a distributed deployment.

## Performance Considerations

The fix adds a small, constant-time check (`Math.rint` plus two comparisons) on the already-rare path of applying a declared default — not a hot path, and not something that could plausibly regress rendering throughput. The more interesting performance-adjacent decision was the one made in review and *not* taken: switching the YAML parser to `USE_BIG_DECIMAL_FOR_FLOATS` would have changed the representation (and therefore the performance characteristics and memory footprint) of **every** floating-point value parsed from **every** template in the system, for a correctness benefit that only matters for defaults exceeding `2^53` — correctly judged not worth the blast radius.

## Testing

Four new JUnit 5 tests, each asserting a specific, concrete value (an exact rendered string, or an exact variable name plus expected-type string on a validation error) rather than a loose "no error"/"not null" check — explicitly aligned with the project's stated testing convention that assertions must check specific values. The tests deliberately cover all four quadrants of the fix's logic: whole-number-and-in-range (should coerce and pass), whole-number-and-out-of-range (should still fail), fractional (should still fail), and sibling-type `number` (should be completely unaffected).

---

# Engineering Decisions

## Decision 1 — Coerce only whole-number decimals, never all `Double` values

Coercing *any* `Double` default to `Long` for an `integer`-typed variable would have silently accepted genuinely fractional defaults like `5.5`, which is wrong — JSON Schema semantics (which this feature's typing loosely follows) treat `5.0` as a valid integer but `5.5` as not. Restricting the coercion to values that pass `doubleValue == Math.rint(doubleValue)` keeps the fix exactly as narrow as the bug, confirmed correct by the maintainer's explicit comparison to JSON Schema's own definition of "integer" during review.

## Decision 2 — Scope the fix to defaults only, not caller-supplied values

A nearly identical bug exists for caller-supplied values (`{"max_results": 7.0}` is also incorrectly rejected today). I deliberately did not fix that in this PR, even after a maintainer flagged it as a legitimate, closely related issue, because it was outside what the linked, maintainer-triaged issue (#10016) asked for. Keeping the PR matched to its approved issue kept the review surface small and the change easy to reason about; the asymmetry is now tracked as a named follow-up rather than silently left undocumented.

## Decision 3 — An explicit bounds check instead of trusting `Double.longValue()`

`Double.longValue()`'s silent-saturation behavior on overflow is a well-known Java footgun, and my first draft of this fix walked straight into it. Once Copilot's review surfaced it, the fix was to add an explicit numeric range check *before* the narrowing conversion, using bound constants chosen for exact `double` representability rather than a naive cast of `Long.MAX_VALUE`. The alternative — switching the whole YAML parser to arbitrary-precision `BigDecimal` via `USE_BIG_DECIMAL_FOR_FLOATS` — was explicitly considered and rejected as disproportionate to the actual bug (it would change every floating-point value's Java type across the entire template-rendering feature, including unrelated `number` variables, to fix an edge case above `2^53` that a real prompt template is very unlikely to ever hit).

## Decision 4 — Bundle the SonarCloud literal-extraction cleanup into the same PR rather than a second one

The project's contributor checklist enforces "one PR at a time." Rather than opening a second, parallel PR to satisfy a SonarCloud maintainability finding raised against *this* PR's own diff, I folded the six-constant extraction into the same PR as a separate, clearly labeled commit (`refactor(rest): extract prompt template type-name literals to constants`). This kept the rule's spirit (no unrelated parallel PRs) while still landing a reasonable, low-risk cleanup that was a direct consequence of this PR's own changes.

---

# Challenges

## Challenge 1 — A ~40-day wait for the first maintainer review on a long-lived branch

The PR sat without a substantive human maintainer review for roughly 40 days (from 2026-09-06 to `jsenko`'s first review on 2026-10-16), long enough that the repository's own lifecycle bot auto-applied a `lifecycle/review-overdue` label at the 30-day mark and explicitly reassured me the PR would not be auto-closed for inactivity while waiting on the maintainers.

### How I Solved It

I proactively, but not pushily, pinged different maintainers across the wait (`@paoloantinori` and `@EricWittmann` on day one, `@carlesarnal` on day nine and again a month later) rather than repeatedly re-pinging the same person. In parallel, I kept the branch merged up to date against `main` roughly every one to two weeks (nine merge commits across the PR's lifetime) specifically so that, whenever a maintainer did have time, the PR would still be cleanly mergeable rather than stale and conflicted.

### What I Learned

Keeping a long-lived PR continuously rebased/merged against a fast-moving `main` is a discipline worth investing in on its own — it's much cheaper to resolve small conflicts incrementally, commit by commit, than to face one enormous conflict the day a maintainer finally has bandwidth to review.

## Challenge 2 — Absorbing an unrelated upstream package-rename refactor mid-review

While my PR was waiting on review, an unrelated upstream PR (#10426) reorganized the agents package structure, physically moving both files I was editing from `io.apicurio.registry.services.*` to `io.apicurio.registry.agents.services.*`.

### How I Solved It

I merged `upstream/main` into my branch and let Git's rename detection handle it — it resolved as a clean, rename-only merge with no manual conflict markers. I then explicitly verified, rather than assumed, that the merge hadn't pulled in anything unrelated, by running `git diff upstream/main...HEAD` and confirming it touched exactly the two files I expected, at their new package paths, with my fix's logic (the `Double`-to-`Long` coercion, the new constants, and the regression tests) intact. I posted this verification in writing on the PR so the reviewer wouldn't need to re-derive it themselves.

### What I Learned

A large structural refactor landing on `main` while your own PR is in flight is not automatically something to worry about — Git's rename detection is genuinely good at this — but it *is* something to explicitly re-verify after the fact (diff scope, test pass) rather than silently trust, especially when the refactor touches the exact files your fix lives in.

## Challenge 3 — A self-introduced correctness bug in the first version of the fix

My first version of the core fix was logically correct for the bug in the issue, but introduced a new, more dangerous bug of its own: a silent numeric-saturation path. This wasn't caught by my own initial test suite — only by a layer of defense I didn't write myself.

### How I Solved It

GitHub Copilot's automated PR review bot flagged the saturation risk directly, with the specific line it applied to. I fixed it the same day with an explicit, carefully-bounded range check (see **Engineering Decisions**, Decision 3) and added a dedicated regression test using a deliberately extreme out-of-range literal (`1e20`) so the exact failure mode Copilot described could never silently recur.

### What I Learned

`Double`-to-integral narrowing conversions in Java (`longValue()`, `intValue()`, etc.) do not throw on overflow — they saturate silently — which makes them a genuine hazard at any boundary that converts user- or schema-supplied floating-point input into an integral type. Any code doing that conversion at a trust boundary needs an explicit, tested range check, not just a "is this a whole number" check; those are two independent conditions, and I had initially only checked one of them.

---

# Collaboration

## Maintainer / Contributor Interaction

I filed and self-assigned the root-cause issue (#10016) the same day I opened the fix, giving the maintainers a complete, independently-verified root-cause write-up up front rather than asking them to diagnose the bug themselves. Across the review wait I tagged three different maintainers at different points rather than repeatedly pinging one person, and I responded to the repository's own automated "review overdue" notice by simply continuing to keep the branch current rather than escalating.

## Code Review

The PR went through two layers of review: an automated layer (GitHub Copilot's PR reviewer, which caught a real correctness bug — the saturation issue — that my own tests had missed) and a human layer (a project MEMBER, `jsenko`, whose review comment explicitly separated "verified by running," "verified by probe," and "read, not run" claims, modeling a disciplined, honest standard for what a reviewer actually checked versus assumed).

## Design Discussions

The three optional-item exchange (O1/O2/O3) is a clean example of structured review resolution: the reviewer proposed three independent, individually labeled, explicitly non-blocking suggestions; I replied to each one by name with a concrete decision rather than a single blanket response; and the reviewer then re-verified my O2 fix line-by-line rather than taking my word for its safety, confirming each of the three excluded edge cases (`+Infinity`, `-Infinity`, `NaN`) individually before re-approving.

## Collaboration Skills Demonstrated

Patience through a seven-week review wait without becoming confrontational with maintainers; disciplined scope management under review pressure (resisting a legitimate invitation to expand the fix to caller-supplied values); transparent, itemized responses to feedback instead of vague "fixed" comments; proactive, continuous rebasing to keep a long-lived branch reviewable at any moment; and writing review-facing explanations (the merge-verification comment, the O1/O2/O3 responses) that gave the reviewer enough to trust the change without re-deriving it themselves.

---

# Outcomes

## Code

Merged into `main`; net diff **+145 / −15** lines across `PromptRenderingService.java` (+52/−15) and `PromptRenderingServiceTest.java` (+93/0); part of release milestone **3.4.0**.

## Project Impact

Closes a real, reproducible validation defect in the registry's AI/agent prompt-rendering feature, with the fix scoped tightly enough (whole-number-only, `integer`-type-only, bounds-checked) that it introduces no new false negatives — verified by dedicated regression tests covering every adjacent case the fix must *not* accidentally also change.

## User / Developer Impact

Anyone authoring a prompt template with an `integer`-typed variable can now write its default the most natural way (`5.0`, matching how many YAML authors instinctively write whole numbers) without needing to know an internal Jackson deserialization detail to avoid a confusing false-positive validation error.

## Recognition

Approved and merged by a project MEMBER with a detailed, verification-backed review that explicitly praised the test suite ("a good addition") for covering the out-of-range saturation case that `Double.longValue()` would otherwise quietly mishandle, and confirmed DCO sign-off was present on every substantive commit.

---

# Skills Demonstrated

## Programming

Java 21; precise reasoning about IEEE 754 floating-point representability and narrowing-conversion semantics; defensive numeric boundary-condition coding; Jackson `ObjectMapper`/YAML deserialization internals.

## Software Engineering

Root-cause analysis backed by an independent, minimal repro before touching the real codebase; disciplined PR scoping; responding to automated *and* human code review with concrete, individually-justified decisions rather than blanket fixes; writing regression tests that assert specific values across every logically distinct branch of a fix.

## Systems

Understanding of a layered validation pipeline (structural template validation vs. per-value type/range validation) well enough to confirm, by reading rather than assuming, that a fix was needed in exactly one place and not duplicated elsewhere.

## Distributed Systems

Working familiarity with a multi-storage-variant architecture (in-memory, SQL across three dialects, KafkaSQL, GitOps, Kubernetes ConfigMap) and the project convention that storage-layer changes must be validated across all variants — context that correctly informed *not* needing cross-variant testing for this particular fix, since the bug lived entirely in request-time validation logic independent of storage backend.

## Infrastructure / Cloud

Familiarity with a large polyglot Maven reactor's tiered build system, a Quarkus dual-profile (dev/prod) runtime configuration model, and a GitHub Actions-based CI pipeline with a lifecycle bot, SonarCloud quality gating, and an automated-plus-human two-layer PR review process.

## Open Source

End-to-end open-source contribution lifecycle: filing and self-triaging an issue, opening and maintaining a PR through a long review cycle, Conventional Commits and DCO compliance, responding professionally and substantively to both automated and human reviewers, and keeping a long-lived branch rebased through an unrelated concurrent refactor without losing the fix's integrity.

---

# Evidence

| Evidence | URL / Reference | Description |
|---|---|---|
| Repository | https://github.com/Apicurio/apicurio-registry | Apicurio Registry — Apache-2.0 API/schema registry, 949★ / 652 forks |
| Pull Request | https://github.com/Apicurio/apicurio-registry/pull/10017 | "fix(rest): accept whole-number decimal literals for integer prompt template defaults" — merged |
| Issue | https://github.com/Apicurio/apicurio-registry/issues/10016 | Root-cause issue I filed and self-assigned — closed on merge |
| Commit | `79af1eb5` | Core fix commit — `Fixes #10016` |
| Commit | `1ceea814` | SonarCloud literal-extraction refactor |
| Commit | `e393243e` | Bounds-check fix in response to Copilot review |
| Commit | `847f7f73` | O2 cleanup (redundant `isInfinite()` removal) in response to maintainer review |
| Merge commit | `mergedAt: 2026-10-26T14:27:24Z` | Final merge into `main` |
| Release | Milestone `3.4.0` | Target release for both the PR and the linked issue |

---

# Key Technical Keywords

Jackson, `ObjectMapper`, YAML deserialization, JSON Schema type semantics, IEEE 754 double-precision floating point, floating-point-to-integral narrowing conversion, silent numeric saturation, `Double.longValue()`, exact representability of powers of two in `double`, type coercion, schema validation, regression testing, JUnit 5, SonarCloud static analysis, GitHub Copilot automated code review, Conventional Commits, DCO (Developer Certificate of Origin), Apache 2.0 license, Apicurio Registry, Quarkus, AI/agent prompt templates, Maven multi-module reactor, GitHub Actions CI, ArchUnit architectural boundary testing.

---

# Related Work

- **Issue/PR #9309** — the earlier change that introduced `validateAppliedDefaults()`, the mechanism that caused every declared default (not just caller-supplied values) to be run through type validation, and which is therefore the precondition that exposed this bug.
- **PR #10426** — an unrelated agent-registry package reorganization that moved `PromptRenderingService` and its test from `io.apicurio.registry.services.*` to `io.apicurio.registry.agents.services.*` while my PR was in flight; absorbed via a clean, rename-only merge.
- **Follow-up (O1), tracked but not yet filed as of this record** — extending the same whole-number-decimal coercion to *caller-supplied* values (not just declared defaults), so that a caller passing `{"max_results": 7.0}` is accepted the same way a default of `5.0` now is. My own local working branch, `fix/prompt-render-integer-supplied-decimal`, with a commit titled "test(rest): add endpoint coverage for integer prompt variable coercion," appears to be exactly this follow-up work in progress.
- **Tried & Rejected list** (project discussion #8364) — the project maintains a standing list of previously evaluated-and-rejected approaches; `USE_BIG_DECIMAL_FOR_FLOATS` as a parser-wide fix for the `2^53` precision edge case (O3) was considered and rejected in this PR's own review thread for reasons consistent with that list's spirit, though it was not itself a pre-existing entry on it.

---

# Timeline

| Date | Event |
|---|---|
| 2026-09-06 | Issue #10016 filed with full root-cause analysis and independent Jackson repro; self-assigned via `/assign-me` |
| 2026-09-06 | PR #10017 opened with the initial fix (commit `79af1eb5`) |
| 2026-09-06 | SonarCloud maintainability finding addressed same day (commit `1ceea814`); maintainers `@paoloantinori`/`@EricWittmann` pinged for review |
| 2026-09-15 | Branch merged with `main`; `@carlesarnal` pinged for review |
| 2026-09-21 / 2026-09-29 | Further merges to keep branch current against `main` |
| 2026-10-05 | GitHub Copilot review #1: flags silent saturation of out-of-range decimal defaults (High severity); fixed same day (commit `e393243e`); `@carlesarnal` pinged again |
| 2026-10-06 | Rename-only merge absorbs upstream PR #10426's package reorg; repo's lifecycle bot posts a 30-day "review overdue" notice, confirming the PR will not be auto-closed |
| 2026-10-07 | GitHub Copilot review #2: flags double-precision edge case above `2^53` (High severity); discussed, ultimately not changed |
| 2026-10-13 / 2026-10-16 (early) | Further merges to stay current against `main` |
| 2026-10-16 13:09 | Maintainer `jsenko` reviews, approves, raises three optional items (O1/O2/O3); full verification suite starts |
| 2026-10-16 15:31 | I respond to all three items individually: "O1 issue, O2 here, O3 skip" |
| 2026-10-16 16:05 | O2 fix pushed (commit `847f7f73`) |
| 2026-10-16 21:51 | `jsenko` re-approves, independently re-verifies the O2 fix's safety |
| 2026-10-16 22:35 | Full verification suite run flags two unrelated flaky test retries, correctly not attributed to this PR |
| 2026-10-18 | Final upstream merge; SonarCloud Quality Gate passes with zero accepted issues |
| 2026-10-26 | PR #10017 merged into `main`; issue #10016 closed; shipped as part of milestone 3.4.0 |

---

# Notes

- This record was reconstructed directly from the live GitHub PR (#10017), its linked issue (#10016), its full commit history, its diff, and its review/comment threads, plus the repository's own `CLAUDE.md`, `DEVELOPING.md`, and `.checkstyle/checkstyle.xml`-derived conventions — not from memory or assumption. All dates, commit hashes, test counts, and quoted error strings are taken verbatim from those sources as of 2026-11-03.
- The one piece of forward-looking information in this record — the O1 follow-up (caller-supplied decimal coercion) — is inferred from the current local git branch name and a local commit message (`fix/prompt-render-integer-supplied-decimal`, "test(rest): add endpoint coverage for integer prompt variable coercion") rather than from a merged or even yet-opened PR, and is flagged as such above rather than presented as completed work.
