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
27 changes: 27 additions & 0 deletions docs/src/content/docs/cli/lifecycle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,33 @@ Each **unobserved** entry names a reason: `read failed`, `no credentials`, `no b

Drifted entries include attribute-level deltas (`status`, `physicalId`, `lastUpdated`, and each `attributes.*` key).

#### The resolved query address

When the lexicon reports one, each entity also carries the **resolved address its live read was issued against** — for k8s the exact request path, with any defaulting the client applied made visible. This is what separates "confirmed not there" from "looked in the wrong place": a k8s object declared without `metadata.namespace` (a Flux-managed one, say, whose namespace is stamped at apply time) is read from the *default* namespace, and only the address shows that.

```
MISSING (declared, provider reports not in cloud):
- web [queried /apis/apps/v1/namespaces/default/deployments/web]
```

In `--json`, the addresses arrive as `resources.queried` per lexicon — a `name → address` map covering every entity a read was issued for — and each `resources.unobserved[]` row carries its own `queried` field inline:

```json
{
"k8s": {
"resources": {
"missing": ["web"],
"queried": { "web": "/apis/apps/v1/namespaces/default/deployments/web" },
"unobserved": [
{ "name": "api", "reason": "read-failed", "detail": "…", "queried": "/api/v1/namespaces/default/services/api" }
]
}
}
}
```

The field is optional and purely diagnostic: verdicts are unchanged, and a lexicon that reports no addresses simply omits it. `lifecycle plan --json` carries the same address per entry as `queried` on the change set (a `create`'s address is the one the provider confirmed absent). The k8s lexicon is the first implementer.

#### Property-level drift

A lexicon that also implements `observeResourcesDeep()` ([coverage](/chant/lexicons/overview/#runtime-observation-coverage)) adds a second section per lexicon, comparing **property trees** rather than metadata. It reports what the categories above cannot: a property that changed, a property source never declared at all (the console edit CloudFormation's own drift detection does not see), and a declared property the cloud is not carrying.
Expand Down
26 changes: 26 additions & 0 deletions docs/src/content/docs/lexicon-authoring/observation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,32 @@ Returning the bare `Record<string, ResourceMetadata>` map is still valid and mea

Throwing is the whole-lexicon failure — core catches it and marks **every** declared entity `read-failed`, so a broken read never arrives downstream as an empty environment. Failing the whole snapshot because one Deployment is gone still defeats the point; catch per-resource errors and classify them.

### Say where you looked: the resolved query address

An absence is only as trustworthy as the address behind it. When the read address is *derived* — a Kubernetes namespace defaulted from the context, an endpoint override, a region, an account — "the provider said no" and "I asked the wrong place" produce identical verdicts, and the consumer cannot tell them apart. The motivating case (chant #1620): a Flux-deployed object declares no `metadata.namespace` because the controller stamps `targetNamespace` at apply time, so the live read scopes to `default`, finds nothing, and correctly reports absence — painting weeks-old running infrastructure as pending.

The envelope carries an optional `queried` map for this — the resolved address each read was actually issued against, keyed by entity name:

```typescript
const queried: Record<string, string> = {};
// k8s: the exact request path, namespace defaulting made visible
const address = await client.pathFor(ref); // "/apis/apps/v1/namespaces/default/deployments/web"
if (address) queried[entityName] = address;

return observation(resources, unobserved, queried);
```

Rules:

- **Purely additive.** `queried` never changes a verdict; classification reads only `resources` and `unobserved`, and the tri-state above does not shift. An entity in `queried` and neither map is still observed-absent.
- **It is the only record an absence gets.** Absence is spelled "in neither map", so there is no row to hang diagnostics on — the `queried` map is where an absent verdict says which address answered not-found.
- **Unobserved entries can carry it inline** via `UnobservedEntity.queried`, so a failed-read row renders without a join.
- **Omitting it stays valid.** A lexicon with nothing derived about its addresses can skip it entirely.

The harness (`observeEntities`, below) collects it for you: every `EntityObservation` variant — `present`, `absent`, `unobserved` — accepts an optional `queried` string.

Downstream, `chant lifecycle diff --live --json` passes the map through as `resources.queried` per lexicon and joins it onto unobserved rows, so a consumer can render `queried: /apis/apps/v1/namespaces/default/deployments/web → 404` next to a pending verdict — see [`chant lifecycle`](/chant/cli/lifecycle/).

### Unknown entity types are unobserved, not absent

Lexicons grow new resource types over time. If your describe path doesn't cover a type yet, say so per entity — a warning alone is invisible to `lifecycle plan`, which is exactly where the wrong `create` gets proposed:
Expand Down
21 changes: 19 additions & 2 deletions lexicons/k8s/src/api/classify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,30 @@ describe("classifyApiFailure", () => {
}
});

test("the context note survives the one-line cap rather than truncating with the message (#1488)", () => {
test("the context note leads the detail, so it survives the one-line cap and any consumer truncation (#1488, #1620)", () => {
const err = new K8sApiError(500, "InternalError", "x".repeat(500));
err.contextNote = 'context "prod-eks" (bound by k8s.profiles.prod.context)';
const outcome = classifyApiFailure(err);
expect(outcome.kind).toBe("unobserved");
if (outcome.kind === "unobserved") {
expect(outcome.detail.endsWith('context "prod-eks" (bound by k8s.profiles.prod.context)')).toBe(true);
expect(outcome.detail.startsWith('context "prod-eks" (bound by k8s.profiles.prod.context)')).toBe(true);
// The error itself still follows — leading with the cluster does not
// cost the message.
expect(outcome.detail).toContain("xxx");
}
});

test("the context appears within the first 160 chars of a long multi-line error's detail (#1620)", () => {
// behold's estate overlay truncates a reason to its first line / 160 chars;
// the context must land inside that window or it vanishes exactly on the
// failures long enough to need it.
const err = new K8sApiError(500, "InternalError", `${"y".repeat(300)}\n${"z".repeat(300)}`);
err.contextNote = 'context "prod-eks" (bound by k8s.profiles.prod.context)';
const outcome = classifyApiFailure(err);
expect(outcome.kind).toBe("unobserved");
if (outcome.kind === "unobserved") {
const firstLine = outcome.detail.split("\n")[0];
expect(firstLine.slice(0, 160)).toContain('context "prod-eks" (bound by k8s.profiles.prod.context)');
}
});

Expand Down
7 changes: 5 additions & 2 deletions lexicons/k8s/src/api/classify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,10 @@ function detailOf(err: unknown): string {
const capped = line.length > 200 ? `${line.slice(0, 197)}...` : line;
// #1488 — a reason that does not say which cluster was read turned an
// ambient-context switch into an afternoon. The client stamps the context it
// resolved onto every failure; append it after the cap so it never truncates.
// resolved onto every failure. The note LEADS the detail (#1620): consumers
// truncate a reason to its first line and ~160 chars, and a note appended
// after a long error is cut off exactly when the error is long enough to
// need it. Leading, it survives any suffix truncation.
const note = shapeOf(err).contextNote;
return note ? `${capped} — ${note}` : capped;
return note ? `${note} — ${capped}` : capped;
}
75 changes: 75 additions & 0 deletions lexicons/k8s/src/describe-resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,81 @@ describe("k8s describeResources", () => {
expect(result.unobserved ?? {}).toEqual({});
});

// The behold#192 shape (#1620): a Flux-deployed object declares no
// metadata.namespace (the controller stamps targetNamespace at apply), so the
// live read scopes to the client's default namespace, finds nothing, and
// correctly reports absence. Every layer is spec-correct and the picture
// still says the opposite of the truth — unless the report carries the
// address it actually asked, which is what `queried` is.
test("an absent verdict carries the resolved query address, namespace defaulted and visible (#1620)", async () => {
const cluster = fakeCluster({
// The object lives where Flux put it — not where the read will look.
objects: { [objectKey("apps/v1", "Deployment", "web", "flux-target")]: web },
});
const result = await describeResources(
{
environment: "prod",
buildOutput: "",
entityNames: ["web"],
entities: makeEntities([
// No metadata.namespace declared — Flux stamps it at apply time.
{ name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web" } } },
]),
},
cluster.connector,
);

// Still a clean absence: in neither map, the tri-state unshifted.
expect(result.resources).toEqual({});
expect(result.unobserved ?? {}).toEqual({});
// But the report can now explain itself: the read went to `default`.
expect(result.queried?.web).toBe("/apis/apps/v1/namespaces/default/deployments/web");
});

test("a present entity carries its query address too — the map is total over issued reads (#1620)", async () => {
const cluster = fakeCluster({
objects: { [objectKey("apps/v1", "Deployment", "web", "prod")]: web },
});
const result = await describeResources(
{
environment: "prod",
buildOutput: "",
entityNames: ["web"],
entities: makeEntities([
{ name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web", namespace: "prod" } } },
]),
},
cluster.connector,
);
expect(result.resources.web).toBeDefined();
expect(result.queried?.web).toBe("/apis/apps/v1/namespaces/prod/deployments/web");
});

test("a read-failed unobserved entry carries the address the failing read was issued against (#1620)", async () => {
const cluster = fakeCluster({
respond: (req) =>
req.path.endsWith("/deployments/web")
? { status: 500, body: statusBody(500, "InternalError", "etcdserver: request timed out") }
: undefined,
});
const result = await describeResources(
{
environment: "prod",
buildOutput: "",
entityNames: ["web"],
entities: makeEntities([
{ name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web", namespace: "prod" } } },
]),
},
cluster.connector,
);
expect(result.unobserved?.web).toMatchObject({
reason: "read-failed",
queried: "/apis/apps/v1/namespaces/prod/deployments/web",
});
expect(result.queried?.web).toBe("/apis/apps/v1/namespaces/prod/deployments/web");
});

// The headline of chant #1074: the twenty-entry map is gone, so a CRD is an
// ordinary read rather than a permanent hole.
test("a CRD is observed like anything else — no KUBECTL_RESOURCE entry required", async () => {
Expand Down
47 changes: 38 additions & 9 deletions lexicons/k8s/src/describe-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,14 @@ export async function describeResources(
): Promise<ObservationResult> {
const resources: Record<string, ResourceMetadata> = {};
const unobserved: Record<string, UnobservedEntity> = {};
// The resolved query address per declared entity (#1620) — the exact request
// path each read was issued against, with the namespace the client actually
// defaulted to when the declaration carries none. This is what lets an
// absence explain itself: a Flux-deployed object declaring no
// metadata.namespace reads from `default`, correctly comes back 404, and
// without the address the report says "not there" when the truth is "not
// looked for where it lives".
const queried: Record<string, string> = {};

const declared: Declared[] = [...options.entities].map(([entityName, entity]) => ({
entityName,
Expand Down Expand Up @@ -323,13 +331,27 @@ export async function describeResources(
return;
}

const ref = {
apiVersion: operation.apiVersion,
kind: operation.kind,
name,
...(metadata?.namespace ? { namespace: metadata.namespace } : {}),
};

// Resolve the address BEFORE the read, so every verdict below — present,
// absent, filtered, read-failed — carries the same record of what was
// asked. Resolution rides the client's cached discovery; a kind discovery
// does not serve has no path, and a resolution failure classifies through
// the read below, never here.
try {
const address = typeof client.pathFor === "function" ? await client.pathFor(ref) : undefined;
if (address) queried[entityName] = address;
} catch {
// The read below hits the same resolution and classifies its failure.
}

try {
const obj = await client.read({
apiVersion: operation.apiVersion,
kind: operation.kind,
name,
...(metadata?.namespace ? { namespace: metadata.namespace } : {}),
});
const obj = await client.read(ref);

// owned filter: withhold resources not carrying chant's marker label.
// Withheld is not absent (chant #1089) — this object exists, it just
Expand All @@ -340,6 +362,7 @@ export async function describeResources(
type: entityType,
reason: "filtered",
detail: "live object carries no chant ownership marker and --owned was requested",
...(queried[entityName] ? { queried: queried[entityName] } : {}),
};
return;
}
Expand All @@ -361,16 +384,22 @@ export async function describeResources(
} catch (err) {
const outcome = classifyApiFailure(err);
if (outcome.kind === "unobserved") {
unobserved[entityName] = { type: entityType, reason: outcome.reason, detail: outcome.detail };
unobserved[entityName] = {
type: entityType,
reason: outcome.reason,
detail: outcome.detail,
...(queried[entityName] ? { queried: queried[entityName] } : {}),
};
}
// `absent` deliberately records nothing: in neither map is how the
// contract spells "asked, and it is not there".
// contract spells "asked, and it is not there". Its address stays in
// `queried` (#1620), which is the only record an absence gets.
}
});

await addRuntimeChildren(client, resources, unobserved, options.owned, declared);

return observation(resources, unobserved);
return observation(resources, unobserved, queried);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/cli/handlers/components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ export async function runComponentsStatus(ctx: CommandContext): Promise<number>
// rather than "stale" (recorded, and nothing live).
const message = err instanceof Error ? err.message : String(err);
console.error(formatWarning({ message: `${plugin.name}: describeResources failed — ${message} (components in this lexicon report unknown, not stale)` }));
observed = { resources: {}, unobserved: unobservedAll(declared, "read-failed", message, entities) };
observed = { resources: {}, unobserved: unobservedAll(declared, "read-failed", message, entities), queried: {} };
}
const cs = buildChangeSet(environment, {
declared,
Expand Down
10 changes: 8 additions & 2 deletions packages/core/src/cli/handlers/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,7 @@ async function observeLexicon(
return {
resources: {},
unobserved: unobservedAll(entityNames, "read-failed", message, opts.entities),
queried: {},
};
}
}
Expand Down Expand Up @@ -806,7 +807,7 @@ async function runLifecycleDiffLive(args: LiveDiffArgs): Promise<LiveDiffOutcome
});
const observedNow = observed.resources;
const observedThen = prevSnapshot?.resources;
const diff = diffLive({ declared, observedNow, observedThen, unobserved: observed.unobserved });
const diff = diffLive({ declared, observedNow, observedThen, unobserved: observed.unobserved, queried: observed.queried });
// Unobserved entities are deliberately NOT drift: a hole in the read is
// not a change in the cloud. They are reported separately (#1089) so a
// "no drift detected" line can never be built on top of a failed read.
Expand Down Expand Up @@ -962,7 +963,12 @@ function renderLiveDiff(lexiconName: string, environment: string, diff: LiveDiff
}
if (diff.missing.length > 0) {
console.log(formatBold("\nMISSING (declared, provider reports not in cloud):"));
for (const name of diff.missing) console.log(` - ${name}`);
for (const name of diff.missing) {
// The address the read actually went to (#1620) — the line between "not
// there" and "looked in the wrong place" (a defaulted namespace, say).
const queried = diff.queried?.[name];
console.log(` - ${name}${queried ? ` [queried ${queried}]` : ""}`);
}
}
if (diff.orphan.length > 0) {
console.log(formatBold("\nORPHAN (in cloud, not declared):"));
Expand Down
26 changes: 26 additions & 0 deletions packages/core/src/lifecycle/change-set.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,32 @@ describe("buildChangeSet: not-observed is not absent (#1089)", () => {
expect(cs.entries.find((x) => x.name === "crd-widget")!.action).toBe("create");
});

test("a create carries the address the provider confirmed absent, when the lexicon reported one (#1620)", () => {
const cs = buildChangeSet("prod", {
declared: new Set(["web"]),
observedNow: {},
observedThen: undefined,
queried: { web: "/apis/apps/v1/namespaces/default/deployments/web" },
});
const e = cs.entries.find((x) => x.name === "web")!;
// The verdict is unchanged — the address is diagnostic, never load-bearing.
expect(e.action).toBe("create");
expect(e.queried).toBe("/apis/apps/v1/namespaces/default/deployments/web");
});

test("an unobserved entry's own queried address wins over the map (#1620)", () => {
const cs = buildChangeSet("prod", {
declared: new Set(["web"]),
observedNow: {},
observedThen: undefined,
unobserved: { web: { reason: "read-failed", queried: "from-entry" } },
queried: { web: "from-map" },
});
const e = cs.entries.find((x) => x.name === "web")!;
expect(e.action).toBe("unobserved");
expect(e.queried).toBe("from-entry");
});

test("a returned resource wins over an unobserved claim for the same name", () => {
const cs = buildChangeSet("prod", {
declared: new Set(["queue"]),
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/lifecycle/change-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ export interface ChangeSetEntry {
unobservedReason?: UnobservedReason;
/** Human-readable backing for `unobservedReason` (the failing command, the missing binding). */
unobservedDetail?: string;
/**
* The resolved address the live read was issued against (#1620), when the
* lexicon reported one. On a `create` it says which address the provider
* confirmed absent — the line between "not there" and "looked in the wrong
* place" (a defaulted namespace, an endpoint override, the wrong region).
*/
queried?: string;
/** The declared entity this resource's owner chain resolves to, for `action: "runtime"` (#1077). */
runtimeOwner?: string;
}
Expand Down Expand Up @@ -172,6 +179,11 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet {
action = "noop";
}

// The address the read went to (#1620) — from the unobserved entry when
// there is one, else the observation's queried map. Diagnostic only; the
// classification above never reads it.
const queried = unobservedEntry?.queried ?? input.queried?.[name];

entries.push({
name,
type,
Expand All @@ -185,6 +197,7 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet {
...(unobservedEntry.detail ? { unobservedDetail: unobservedEntry.detail } : {}),
}
: {}),
...(queried ? { queried } : {}),
...(runtimeOwner ? { runtimeOwner } : {}),
});
}
Expand Down
Loading
Loading