Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Contract: Doctor root-pool diagnostics

**Source**: [spec.md](../spec.md), FR-7 and AC-9, AC-10, NFR-3, NFR-4.
**Existing surfaces**: `cmd/ipam/doctor.go`, `cmd/ipam/output.go`, root `Client`.

## Read-only public diagnostic seam

Add a root-library diagnostic method rather than duplicating private document
codecs in the CLI:

```go
type RootPoolDiagnostic struct {
Check string
PoolIDs []string
Detail string
}

func (c *Client) DiagnoseRootPools(ctx context.Context) ([]RootPoolDiagnostic, error)
```

`Check` is `root-overlap` or `root-registry`; `PoolIDs` are sorted known valid
pool IDs, and `Detail` is static, operator-safe wording. The method performs no
create, put or delete. Storage/decoding failures return no partial-success claim;
doctor renders an explicit `root-registry` FAIL with an error class, not raw
registry bytes (FR-7, C-I.2, C-V.1; AC-9, AC-10).

## Checks and severity

| Input snapshot | Check | Status | Trace |
| --- | --- | --- | --- |
| Two usable same-family roots have an intersecting canonical CIDR | `root-overlap` | FAIL | FR-7, AC-9, NFR-3 |
| Usable roots are all same-family disjoint and registry membership matches | no negative row; one global PASS may summarize consistency | PASS | NFR-4 |
| Registry absent with one or more usable roots | `root-registry` | FAIL | FR-7, FR-11, AC-10 |
| Registry absent with no usable roots | `root-registry` | PASS (`not initialized; no roots`) | FR-9, AC-1 |
| Invalid/unsupported registry, duplicate entry, invalid state/family/CIDR | `root-registry` | FAIL | FR-7, AC-10 |
| Usable root absent from a present registry, or active entry does not match usable incarnation/family/CIDRs | `root-registry` | FAIL | FR-7, AC-10 |
| `pending` or `deleting` entry cannot yet be matched to the final usable/deleted shape | `root-registry` | WARN | FR-7, AC-10; no-auto-repair scope |

Every confirmed overlap pair produces one row with both sorted IDs. WARN does
not mean the range is released: pending and deleting claims continue to reserve
it. Existing doctor aggregation remains any FAIL -> `fail`/exit 6, otherwise any
WARN -> `warn`/exit 0, otherwise `pass`/exit 0.

## Example JSON subset

Only fictional identifiers and ranges are allowed in examples. The following is
an illustrative subset, not a claim about the current store:

```json
{
"result": "fail",
"checks": [
{
"check": "root-overlap",
"pool": "example-a,example-b",
"status": "FAIL",
"detail": "usable root pools example-a and example-b overlap in address family 4"
}
]
}
```

Table mode uses the existing `CHECK POOL STATUS DETAIL` columns and `RESULT:`
footer. Check details identify affected pool IDs, state and schema/error class;
they do not contain raw keys, URL, endpoint, credential, backend message, or
untrusted document contents.

## Snapshot rules

1. List every direct usable root through existing pool-document consistency
rules. Child pools do not participate (FR-1, FR-6; AC-15).
2. Compare canonical ranges independently from registry entries so legacy
overlap is found even if the registry is missing or wrong (FR-7, AC-9).
3. Compare the same snapshot with registry membership, state, family,
incarnation and full CIDR list (AC-10).
4. Do not create, replace, delete or “repair” any object, including the registry
and pool documents. Do not retry a diagnostic by publishing (FR-7,
no-auto-repair scope).
5. A single read sequence cannot distinguish a legitimate in-flight `pending`
transition from interruption, so report it as WARN with explicit wording,
never FAIL-to-WARN default fallback and never automatic cleanup (ASM-6).

## Verification

- At least 10 deterministic overlap fixtures cover equal, contained, enclosing
and partial intersections for both families where useful; each reports all
affected pools (NFR-3).
- At least 10 deterministic disjoint or adjacent root sets produce no false
overlap row (NFR-4).
- Recording stores assert zero `CreateIfAbsent`, `PutIfMatch` and `DeleteIfMatch`
calls in root diagnostics (FR-7 and doctor read-only convention).
- Keep doctor permission, output, write-probe and fragmentation behavior under
the existing BASE-0015 and REQ-000070 tests; root diagnostics run only as
additional read-only rows (AC-10).
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Contract: Root-pool overlap coordination

**Source**: [spec.md](../spec.md), FR-1..FR-6, FR-9..FR-11 and AC-1..AC-8,
AC-12..AC-16.
**Consumers**: Root `ipam.Client`, CLI callers and doctor diagnostics.

## Existing public API

Keep these signatures and semantics:

```go
func (c *Client) CreatePool(ctx context.Context, spec PoolSpec) (Pool, error)
func (c *Client) DeletePool(ctx context.Context, poolID string) error
func (c *Client) ListPools(ctx context.Context) ([]Pool, error)
```

No new API is needed to create or configure the registry. The path is internal,
and ordinary reads continue to return `Pool` values without coordination
metadata (FR-2, FR-10; AC-1, AC-2, AC-15).

## Root create outcomes

| Condition | Result | Trace |
| --- | --- | --- |
| Valid disjoint root in a store with no registry/roots | Pool becomes usable; registry contains one `active` entry | AC-1 |
| Disjoint from all applicable roots | Pool becomes usable; its own reservation transitions to `active` | FR-2, AC-2 |
| Same-family canonical range intersects another registry reservation | No proposed pool/state document becomes usable; `*OpError`, `Reason == "overlap"`, `errors.Is(err, ErrConflict)` | FR-3, FR-4, AC-3, AC-4, AC-12, AC-13 |
| Equal/adjacent/mixed scenario | Equal ranges conflict; adjacent ranges succeed; another family succeeds | FR-1, FR-6, AC-3, AC-4, AC-7, AC-8 |
| Concurrent overlapping proposals with normal CAS | Exactly one reservation may become active; loser returns overlap or retries to the existing contention result; never two usable roots | FR-5, AC-5, NFR-1 |
| Identical exact root already usable and active | Existing idempotent success, zero replacement pool-doc writes | FR-10, AC-15 |
| Present registry cannot be decoded | No overwrite or adoption; return the existing unsupported/document error category | FR-7, AC-10 |

The overlap category must not match `ErrInvalidCIDR` or the `pool_exists`
reason. Contention remains a separate result as defined by `client.go` and
BASE-0004. (AC-12.)

## Registry protocol

At every CAS transition, decode the complete current registry, validate the
entry invariants, mutate an isolated copy and encode deterministic JSON before
writing. Opaque `storage.Version` values are round-tripped, never parsed.

Bootstrap and create reservation are one conditional creation when possible:

1. `Get(rootRegistryKey)`.
2. If missing, list/decode all usable roots and build an active snapshot.
3. Check the proposal against every same-family reservation.
4. `CreateIfAbsent` a sorted document containing existing active roots plus the
proposed `pending` entry.
5. If creation loses, reread and repeat the check/`PutIfMatch` transition; never
overwrite an existing key without its exact version.

For an existing registry, add or transition the claim with `PutIfMatch`.
On `ErrUnknownOutcome`, reread and treat the operation as success only if the
exact own entry and document version-independent fields prove this call's write
landed. This follows `CreatePool` and backend-contract patterns; it is not a
blind success fallback. (FR-5, AC-5, NFR-1.)

## Lifecycle integration

- A child pool never reserves a registry entry; its parent allocation remains
the overlap boundary (FR-6 and out of scope).
- A root pending claim precedes both pool document writes. The existing
state/pool `CreateIfAbsent` order and own-incarnation cleanup remain (FR-5,
FR-10; AC-1..AC-5).
- A failed root publication removes only a matching `pending` entry for this
call and only after its own pool documents are absent. Cleanup failure is
joined to the original error so it remains explicit (AC-10, AC-15).
- A root delete checks nonempty and incarnation rules first, CAS-writes
`active|pending -> deleting`, runs the existing document deletion, then
removes the matching `deleting` entry (FR-10; AC-15).
- `pending`, `active` and `deleting` all reserve their ranges. Only removal
after successful lifecycle completion releases a range (FR-3; AC-5).

## Prefix matching

Reuse `canonicalPool` before comparison. For same-family entries and every pair
of prefixes, overlap is `netip.Prefix.Overlaps`; equal, enclosing, contained and
partial intersections all match. Adjacent prefixes and an IPv4/IPv6 pair do
not match. Existing CIDR input acceptance and mapped IPv4 normalization are
unchanged. (FR-1, FR-6, FR-10; AC-3, AC-4, AC-7, AC-8, AC-14.)

## Compatibility and storage permissions

The reserved key starts below the existing `pools/` prefix, uses a leading-dot
basename invalid as a pool ID, and requires the same object capability already
needed to create/delete root pool definitions. Pool listing filters it through
the existing pool-ID parser. Doctor discovery must likewise ignore keys whose
basename is not a valid pool ID (C-I.1, FR-6; AC-6, AC-7).

Pool and allocation-state documents retain existing schema bytes. Existing
stores bootstrap lazily on a root mutation. Mixed old/new writers are not safe
and are outside the concurrent-client guarantee; rollout must quiesce old
versions (ASM-4; FR-5, AC-5, NFR-1).

## Public and documentation vocabulary

Documentation identifies the rule as: “A root pool is rejected when any
canonical CIDR overlaps a root pool of the same address family in the same
store. Doctor reports legacy overlap and registry inconsistency.” It does not
claim cross-store, cross-family or child-pool coordination (FR-8, AC-11 and
out-of-scope set).
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Data model: Root-pool overlap coordination

**Source**: [spec.md](spec.md)
**Design**: [plan.md](plan.md), [root contract](contracts/root-pool-overlap.md)

## Persisted entity: root registry

| Field | Shape | Invariants and lifecycle | Trace |
| --- | --- | --- | --- |
| Storage key | `pools/.root-registry.json` | Reserved internal key, excluded from valid pool IDs. Shared by every root operation in one storage prefix. No new backend or credential key. | FR-1, FR-5, FR-6, AC-5, AC-6, AC-7 |
| `schema_version` | Integer, `1` | Unknown value returns `ErrUnsupportedSchema`; never reinterpret or overwrite automatically. | FR-10, AC-10 |
| `kind` | Literal `root_pool_registry` | Wrong value is an invalid document; codec returns a non-overlap error. | AC-10 |
| `roots` | Array of root entries sorted by `pool_id` | Exactly one entry per pool ID; no child pools. An absent key is bootstrap-capable, a present invalid document is not. | FR-1, FR-6, FR-11, AC-9, AC-10, AC-16 |

## Root entry

| Field | Shape | Invariants and lifecycle | Trace |
| --- | --- | --- | --- |
| `pool_id` | Valid pool ID | Unique. It is the lifecycle and diagnostic identity, never a customer identifier. | FR-10, AC-9, AC-10, AC-12 |
| `incarnation` | Existing 16-byte hex format | Must match both usable pool documents while `active`; retained through `deleting` to prevent adoption by a replacement. | FR-10, AC-15 |
| `family` | Integer `4` or `6` | Must equal the family inferred from every canonical CIDR. | FR-1, FR-6, AC-3, AC-4, AC-7 |
| `cidrs` | Sorted canonical strings | One or more; same-family and internally disjoint under existing `canonicalPool`; full membership is replaceable by a future CAS update. | FR-1, FR-10, AC-13, AC-14; future-prefix constraint |
| `state` | `pending`, `active`, `deleting` | Defines the only legal transitions below. Every state reserves its complete range. | FR-3, FR-5, FR-7, AC-5, AC-10, AC-15 |

Example with fictional pool data:

```json
{
"schema_version": 1,
"kind": "root_pool_registry",
"roots": [
{
"pool_id": "example-root",
"incarnation": "0123456789abcdef0123456789abcdef",
"family": 4,
"cidrs": ["192.0.2.0/24"],
"state": "active"
}
]
}
```

## State transitions

```text
absent --CreateIfAbsent with bootstrap + proposed claim--> pending
active --valid empty DeletePool--> deleting --documents absent + CAS--> absent
pending --own matching documents usable + CAS--> active
pending --owned publication failure, own documents absent + CAS--> absent
pending --valid delete of matching usable empty pool--> deleting
```

1. `pending` means the range is reserved but publication is not yet confirmed.
It can become `active` only after both pool documents match its incarnation
(FR-5, FR-10; AC-1, AC-5).
2. `active` means a usable root exists and registry fields exactly match its
definition. A future prefix update can replace this entry's `cidrs` under one
CAS while preserving the state and incarnation (future-prefix constraint;
AC-16).
3. `deleting` means the range remains reserved while matching pool documents
are removed. It can return to absent only after the current call observes
those documents absent (FR-3, FR-10; AC-15).
4. No path from `deleting` to `active` exists. A replacement root cannot reclaim
the range until the old entry is removed (FR-3, FR-5; AC-5).

## Derived entities

| Entity | Fields | Invariants | Trace |
| --- | --- | --- | --- |
| Canonical proposed root | Pool ID, family, CIDRs, incarnation generated by the call | Uses `canonicalPool`; no mixed family or internal overlap. It does not become usable before registry reservation. | FR-1, FR-10, AC-1..AC-4, AC-13, AC-14 |
| Overlap result | Proposed ID, conflicting ID, same-family matching canonical ranges | Produced only for range intersection; maps to `ErrConflict` reason `overlap`. | FR-4, AC-3, AC-4, AC-12 |
| Root diagnostic | Check name, status, affected pool IDs, static detail | A derivation, not persisted; contains no endpoint, raw registry bytes or credentials. | FR-7, AC-9, AC-10, C-I.2/C-V.1 |
| Bootstrap set | Sorted usable root entries from `ListPools`/matching document pairs | Formed only when the registry key is absent; preserves all usable roots, including legacy overlapping roots for doctor to report. | FR-11, AC-9, AC-16 |

## Consistency rules

- An `active` entry and usable root must match ID, incarnation, family and CIDRs.
- Every usable root must have an entry once a registry is present.
- `pending` and `deleting` may be observed without a usable root. They are a
warning because the read cannot distinguish active work from interruption;
they still reserve their ranges.
- A pending/deleting entry must never be automatically deleted by doctor or a
normal read. A create compensates only its own `pending` entry after proving
its own documents did not publish; a delete completes only a
matching `deleting` entry (FR-5, FR-7; AC-5, AC-10).
- Overlap is strict address intersection. Adjacent ranges do not overlap;
different stores and address families are independent (FR-6; AC-6..AC-8).
- Existing pool and allocation-state documents do not gain fields and retain
their current schema and migration behavior (FR-10; AC-15, AC-16).
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# ADR-0001: Retain the exact-pinned Go library and Cobra CLI stack

**Status**: Proposed for G3
**Trace**: AC-1..AC-16; FR-8; NFR-1..NFR-4; constitution III.

## Context

`go.mod` declares `github.com/appvia/ipam`, Go 1.27.3 and Cobra v1.10.2.
`pool.go`, `client.go`, `storage/storage.go` and `cmd/ipam/doctor.go` already
provide the lifecycle, CAS, retry, storage and diagnostic seams required by the
approved spec. `mise.toml` pins Go 1.27.3 and golangci-lint 2.14.0; CI retains
cross-platform tests, Linux race checks, lint and backend emulator coverage.

The change is one persisted JSON coordination document and a local extension to
pool/doctor behavior. It needs no new service, runtime, SDK or dependency.

## Decision

Implement the design in the existing root Go library and Cobra CLI. Reuse
standard `net/netip`, `errors`, maps/slices and the existing internal document
codec patterns. Add no runtime dependency or tool. Use `make build`, `make test`
and `make lint`; preserve the current `go.mod`/`go.sum`, `mise.toml`, `mise.lock`
and CI workflows.

Use the product's `ac-test-mapping` skill for later Story evidence. No separate
Go stack skill exists in the product checkout, so the commands above are the
explicit build, test and lint contract.

## Alternatives considered

- A separate registry service/database would add availability, deployment,
identity and data-synchronisation concerns without improving one-object CAS
atomicity required by AC-5.
- A new coordination dependency or language would duplicate existing retry,
document and storage behavior and create a toolchain migration outside scope.
- A CLI-only prevention check would not protect library callers and would fail
AC-1 through AC-5.

## Consequences

The feature is covered by the existing tests and release path in one repository.
No package/tool pin changes are needed, and all backends retain their storage
contract. Root registry tests must exercise memory, local and existing emulator
paths without changing provider implementations. Any future dependency or
toolchain need requires a separate design decision.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# ADR-0002: Serialize root overlap decisions in a CAS registry

**Status**: Proposed for G3
**Trace**: FR-1..FR-6, FR-9; AC-1..AC-8, AC-12..AC-14; NFR-1.

## Context

Each root pool is currently represented by an allocation-state document and a
pool definition. There is no shared object across roots. A creator can list
current pools and still race another creator that observed the same snapshot,
so sequential overlap checking is insufficient. The approved requirement
permits only storage conditional writes for correctness.

## Decision

Add one versioned document at `pools/.root-registry.json`. It lists every root
reservation with ID, incarnation, family, canonical CIDRs and lifecycle state.
Root creates read the registry, reject same-family `netip.Prefix.Overlaps`
matches and CAS-add a `pending` entry before publishing pool documents. A
successful reservation is unique by storage conditional semantics. The
document lives below the existing `pools/` capability and uses a basename that
cannot be a valid pool ID.

## Alternatives considered

- List-then-create was rejected because two creators can both observe no roots.
- One object per possible prefix was rejected because intersection spans
arbitrary, nested and partial ranges with no finite precomputed key set.
- A lock file or in-process mutex was rejected because it is not shared reliably
across processes and violates the CAS-only constraint.
- Creating the registry under a new top-level prefix was rejected to avoid
expanding the permissions needed for existing root writers.

## Consequences

All root operations share a small contention point. Disjoint roots may retry
when their registry versions race, bounded by existing client semantics. A
storage backend that ignores CAS cannot provide the invariant; the existing
backend qualification and doctor write probe remain mandatory. The registry's
full CIDR list supports a future CAS replacement when prefix add/remove is
introduced, without changing this design.
Loading
Loading