From 5d94e0d2b4a98a0d5c7301bd602396a92f5e213d Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 24 Aug 2026 23:09:06 -0600 Subject: [PATCH] =?UTF-8?q?feat(aws):=20MonitoringStack=20composite=20?= =?UTF-8?q?=E2=80=94=20dashboard=20+=20metric-tied=20alarms=20(#1139)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The recurring hand-rolled shape the aws-bench corpus surfaced: a dashboard, a metric per resource, and a near-identical alarm next to each one — 44 combined dashboard+alarm+metric instantiations across the corpus, nothing equivalent shipped. Fixed metric1..metric3 slots (an Alarm-array loop is the control-flow-over-resources shape EVL002/EVL003 rule out for reference composites, same reasoning as EksCluster's addon1..addon3). Verified against Floci: a CwDashboard + Alarm pair from this composite deploys via cfn-deploy to CREATE_COMPLETE, and describe-alarms round-trips every property. Two emulator gaps found along the way (CloudWatch's list/get-dashboard both UnsupportedOperation despite CFN reporting the Dashboard created; its physical id ignores the declared DashboardName) — logged in test/floci-gaps.md, entries 11-12, not filed upstream yet. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_013GoZx3iYpaQxKNCNxguYvT --- lexicons/aws/src/composites/index.ts | 2 + .../src/composites/monitoring-stack.test.ts | 130 +++++++++++++++ .../aws/src/composites/monitoring-stack.ts | 156 ++++++++++++++++++ lexicons/aws/src/index.ts | 2 + test/floci-gaps.md | 64 +++++++ 5 files changed, 354 insertions(+) create mode 100644 lexicons/aws/src/composites/monitoring-stack.test.ts create mode 100644 lexicons/aws/src/composites/monitoring-stack.ts diff --git a/lexicons/aws/src/composites/index.ts b/lexicons/aws/src/composites/index.ts index bf2b07f4e5..6e1872a208 100644 --- a/lexicons/aws/src/composites/index.ts +++ b/lexicons/aws/src/composites/index.ts @@ -45,3 +45,5 @@ export { MicrovmApp, MICROVM_LIMITS } from "./microvm-app"; export type { MicrovmAppProps, MicrovmAppResult, MicrovmAppBuildConnectorProps, MicrovmMemoryMiB } from "./microvm-app"; export { AgentCoreAgent, agentCoreDefaultEndpointArn } from "./agentcore-agent"; export type { AgentCoreAgentProps, AgentCoreAgentResult } from "./agentcore-agent"; +export { MonitoringStack } from "./monitoring-stack"; +export type { MonitoringStackProps, MonitoringMetricSpec } from "./monitoring-stack"; diff --git a/lexicons/aws/src/composites/monitoring-stack.test.ts b/lexicons/aws/src/composites/monitoring-stack.test.ts new file mode 100644 index 0000000000..bb001d2209 --- /dev/null +++ b/lexicons/aws/src/composites/monitoring-stack.test.ts @@ -0,0 +1,130 @@ +import { describe, test, expect } from "vitest"; +import { expandComposite } from "@intentius/chant"; +import { MonitoringStack, type MonitoringMetricSpec } from "./monitoring-stack"; + +const errors: MonitoringMetricSpec = { + title: "OrdersFn Errors", + namespace: "AWS/Lambda", + metricName: "Errors", + dimension: { name: "FunctionName", value: "orders-fn" }, + alarm: { threshold: 5 }, +}; + +const duration: MonitoringMetricSpec = { + title: "OrdersFn Duration p99", + namespace: "AWS/Lambda", + metricName: "Duration", + dimension: { name: "FunctionName", value: "orders-fn" }, + statistic: "p99", + period: 60, +}; + +// The composite's return is a union (which alarmN slots are present), and the +// repo-wide typecheck rightly refuses to narrow it structurally — tests go +// through a member map, the same access the expander itself uses. +type Members = Record } | undefined>; + +describe("MonitoringStack", () => { + test("dashboard-only metric: no alarm slot, widget carries namespace/metric/dimension", () => { + const m = MonitoringStack({ metric1: duration }) as unknown as Members; + expect(m.dashboard).toBeDefined(); + expect(m.alarm1).toBeUndefined(); + const body = JSON.parse(m.dashboard!.props!.DashboardBody); + expect(body.widgets).toHaveLength(1); + expect(body.widgets[0].properties.metrics).toEqual([["AWS/Lambda", "Duration", "FunctionName", "orders-fn"]]); + expect(body.widgets[0].properties.stat).toBe("p99"); + expect(body.widgets[0].properties.period).toBe(60); + }); + + test("alarmed metric: alarm1 wired from the same spec, defaults filled in", () => { + const m = MonitoringStack({ metric1: errors }) as unknown as Members; + expect(m.alarm1).toBeDefined(); + const p = m.alarm1!.props!; + expect(p.AlarmName).toBe("OrdersFn Errors"); + expect(p.Namespace).toBe("AWS/Lambda"); + expect(p.MetricName).toBe("Errors"); + expect(p.Dimensions).toEqual([{ Name: "FunctionName", Value: "orders-fn" }]); + expect(p.Statistic).toBe("Sum"); + expect(p.Period).toBe(300); + expect(p.Threshold).toBe(5); + expect(p.ComparisonOperator).toBe("GreaterThanThreshold"); + expect(p.EvaluationPeriods).toBe(1); + }); + + test("three metrics: two alarmed (1, 3), one dashboard-only (2) — slots line up positionally", () => { + const m = MonitoringStack({ + metric1: errors, + metric2: duration, + metric3: { ...errors, title: "OrdersFn Throttles", metricName: "Throttles", alarm: { threshold: 1 } }, + }) as unknown as Members; + expect(m.alarm1).toBeDefined(); + expect(m.alarm2).toBeUndefined(); + expect(m.alarm3).toBeDefined(); + expect(m.alarm3!.props!.MetricName).toBe("Throttles"); + const body = JSON.parse(m.dashboard!.props!.DashboardBody); + expect(body.widgets).toHaveLength(3); + // stacked full-width, one below the last + expect(body.widgets.map((w: any) => w.y)).toEqual([0, 6, 12]); + }); + + test("alarm.dimensionValue overrides the dashboard's literal dimension value (Ref/GetAtt escape hatch)", () => { + const m = MonitoringStack({ + metric1: { ...errors, alarm: { threshold: 5, dimensionValue: { Ref: "OrdersFn" } as any } }, + }) as unknown as Members; + expect(m.alarm1!.props!.Dimensions).toEqual([{ Name: "FunctionName", Value: { Ref: "OrdersFn" } }]); + const body = JSON.parse(m.dashboard!.props!.DashboardBody); + expect(body.widgets[0].properties.metrics[0]).toEqual(["AWS/Lambda", "Errors", "FunctionName", "orders-fn"]); + }); + + test("no dimension: metric tuple is just [namespace, metricName], alarm Dimensions is undefined", () => { + const m = MonitoringStack({ + metric1: { title: "5xx", namespace: "AWS/ApiGateway", metricName: "5XXError", alarm: { threshold: 1 } }, + }) as unknown as Members; + const body = JSON.parse(m.dashboard!.props!.DashboardBody); + expect(body.widgets[0].properties.metrics).toEqual([["AWS/ApiGateway", "5XXError"]]); + expect(m.alarm1!.props!.Dimensions).toBeUndefined(); + }); + + test("alarmActions reach AlarmActions, comparisonOperator/evaluationPeriods/treatMissingData are honored", () => { + const m = MonitoringStack({ + metric1: { + ...errors, + alarm: { + threshold: 100, + comparisonOperator: "LessThanThreshold", + evaluationPeriods: 3, + treatMissingData: "notBreaching", + alarmActions: ["arn:aws:sns:us-east-1:123456789012:pages"], + }, + }, + }) as unknown as Members; + const p = m.alarm1!.props!; + expect(p.ComparisonOperator).toBe("LessThanThreshold"); + expect(p.EvaluationPeriods).toBe(3); + expect(p.TreatMissingData).toBe("notBreaching"); + expect(p.AlarmActions).toEqual(["arn:aws:sns:us-east-1:123456789012:pages"]); + }); + + test("defaults escape hatch reaches the dashboard and a named alarm slot", () => { + const m = MonitoringStack({ + metric1: errors, + dashboardName: "orders-dash", + defaults: { + dashboard: { Tags: [{ Key: "team", Value: "orders" }] }, + alarm1: { DatapointsToAlarm: 2 }, + }, + }) as unknown as Members; + expect(m.dashboard!.props!.DashboardName).toBe("orders-dash"); + expect(m.dashboard!.props!.Tags).toEqual([{ Key: "team", Value: "orders" }]); + expect(m.alarm1!.props!.DatapointsToAlarm).toBe(2); + }); + + test("expandComposite produces stable logical names for dashboard + alarm slots", () => { + const instance = MonitoringStack({ metric1: errors, metric2: duration }); + const expanded = expandComposite("orders", instance); + expect(expanded.has("ordersDashboard")).toBe(true); + expect(expanded.has("ordersAlarm1")).toBe(true); + expect(expanded.has("ordersAlarm2")).toBe(false); + expect(expanded.size).toBe(2); + }); +}); diff --git a/lexicons/aws/src/composites/monitoring-stack.ts b/lexicons/aws/src/composites/monitoring-stack.ts new file mode 100644 index 0000000000..a210dddffc --- /dev/null +++ b/lexicons/aws/src/composites/monitoring-stack.ts @@ -0,0 +1,156 @@ +/** + * MonitoringStack — a CloudWatch dashboard wired to up to three named + * metrics, with an optional alarm per metric. + * + * The recurring hand-rolled shape the aws-bench corpus surfaced: a team + * stands up a `cloudwatch.Dashboard`, a `cloudwatch.Metric` per resource it + * cares about, and a near-identical `cloudwatch.Alarm` next to each one — 44 + * combined dashboard+alarm+metric instantiations across the corpus' 8 real + * CDK apps, nothing equivalent shipped in chant (epic #1139). + * + * Fixed `metric1..metric3` slots, not a `metrics: MetricSpec[]` array — a + * loop building `Alarm` resources from an array is exactly the control-flow- + * over-resources shape EVL002/EVL003 rule out for reference composites (see + * `EksCluster`'s `addon1..addon3`, this directory). A fourth metric is a bare + * `Alarm` + a hand-edited `CwDashboard.DashboardBody` the estate declares + * directly. + * + * What is deliberately NOT here: + * - Notification wiring. `alarm.alarmActions` on each metric takes ARNs the + * caller already has (an SNS topic from `LambdaSns`, or hand-declared); + * this composite does not create a `Topic`/`Subscription` itself — who + * gets paged and on what channel is a real per-estate decision, not a + * default worth guessing. `defaults.alarm1..3` is the escape hatch for + * anything else on the alarm (e.g. `OKActions`, `DatapointsToAlarm`). + * - Math-expression / composite / anomaly-detection alarms (`Alarm.Metrics`, + * `AlarmModel`) — single-metric threshold alarms only. + * - Dynamic (`Ref`/`GetAtt`/`Sub`) values inside the dashboard body. + * `CwDashboard.DashboardBody` is one flat JSON string CloudFormation does + * not template, so each metric's `namespace`/`metricName`/`dimension.value` + * must be a literal the caller already knows — the physical name they set + * on the monitored resource, not one CloudFormation generates. The `Alarm` + * resources carry no such limit: `Dimensions` is a real structured + * property, so `alarm.dimensionValue` accepts `Value` and can + * reference a sibling resource by `Ref`/`GetAtt`. + */ +import { Composite, mergeDefaults, type Value } from "@intentius/chant"; +import { Alarm, CwDashboard } from "../generated"; + +export interface MonitoringMetricSpec { + /** Dashboard widget title, and the alarm's default `AlarmName`. */ + title: string; + /** CloudWatch namespace, e.g. `"AWS/Lambda"`, `"AWS/DynamoDB"`. */ + namespace: string; + /** Metric name within the namespace, e.g. `"Errors"`, `"ConsumedReadCapacityUnits"`. */ + metricName: string; + /** + * Dimension identifying which resource emits the metric, e.g. + * `{ name: "FunctionName", value: "my-fn" }`. Omit for an account/region- + * wide metric. `value` must be a literal — see the dashboard-body note above. + */ + dimension?: { name: string; value: string }; + /** Statistic for both the widget and (if alarmed) the alarm. Default `"Sum"`. */ + statistic?: string; + /** Period in seconds, for both the widget and the alarm. Default `300`. */ + period?: number; + /** Alarm this metric when set; omit for a dashboard-only metric. */ + alarm?: { + threshold: number; + /** Default `"GreaterThanThreshold"`. */ + comparisonOperator?: string; + /** Default `1`. */ + evaluationPeriods?: number; + treatMissingData?: "breaching" | "ignore" | "missing" | "notBreaching"; + /** ARNs to notify on ALARM — an existing SNS topic, typically. */ + alarmActions?: Value[]; + /** + * Dimension value for the alarm. Defaults to `dimension.value`; set this + * instead when the alarm needs to track a `Ref`/`GetAtt` the dashboard + * widget cannot (see the dashboard-body note above). + */ + dimensionValue?: Value; + }; +} + +export interface MonitoringStackProps { + /** `Value`: a name is routinely built with `Sub`/`Ref` (#1366). */ + dashboardName?: Value; + metric1: MonitoringMetricSpec; + metric2?: MonitoringMetricSpec; + metric3?: MonitoringMetricSpec; + tags?: Array<{ Key: string; Value: string }>; + defaults?: { + dashboard?: Partial[0]>; + alarm1?: Partial[0]>; + alarm2?: Partial[0]>; + alarm3?: Partial[0]>; + }; +} + +/** A CloudWatch dashboard "metric" widget, stacked full-width below the last. */ +function widget(spec: MonitoringMetricSpec, index: number) { + const dims = spec.dimension ? [spec.dimension.name, spec.dimension.value] : []; + return { + type: "metric", + x: 0, + y: index * 6, + width: 24, + height: 6, + properties: { + title: spec.title, + metrics: [[spec.namespace, spec.metricName, ...dims]], + period: spec.period ?? 300, + stat: spec.statistic ?? "Sum", + view: "timeSeries", + }, + }; +} + +function alarmProps(spec: MonitoringMetricSpec) { + const a = spec.alarm!; + return { + AlarmName: spec.title, + AlarmDescription: `${spec.title} breached its threshold`, + Namespace: spec.namespace, + MetricName: spec.metricName, + Dimensions: spec.dimension + ? [{ Name: spec.dimension.name, Value: a.dimensionValue ?? spec.dimension.value }] + : undefined, + Statistic: spec.statistic ?? "Sum", + Period: spec.period ?? 300, + Threshold: a.threshold, + ComparisonOperator: a.comparisonOperator ?? "GreaterThanThreshold", + EvaluationPeriods: a.evaluationPeriods ?? 1, + TreatMissingData: a.treatMissingData, + AlarmActions: a.alarmActions, + }; +} + +export const MonitoringStack = Composite((props: MonitoringStackProps) => { + const { defaults } = props; + const specs = [props.metric1, props.metric2, props.metric3].filter( + (s): s is MonitoringMetricSpec => s !== undefined, + ); + + const dashboard = new CwDashboard(mergeDefaults({ + DashboardName: props.dashboardName, + DashboardBody: JSON.stringify({ widgets: specs.map(widget) }), + }, defaults?.dashboard)); + + const alarm1 = props.metric1.alarm + ? new Alarm(mergeDefaults(alarmProps(props.metric1), defaults?.alarm1)) + : undefined; + const alarm2 = props.metric2?.alarm + ? new Alarm(mergeDefaults(alarmProps(props.metric2), defaults?.alarm2)) + : undefined; + const alarm3 = props.metric3?.alarm + ? new Alarm(mergeDefaults(alarmProps(props.metric3), defaults?.alarm3)) + : undefined; + + return { + dashboard, + ...(alarm1 ? { alarm1 } : {}), + ...(alarm2 ? { alarm2 } : {}), + ...(alarm3 ? { alarm3 } : {}), + }; +}, "MonitoringStack"); diff --git a/lexicons/aws/src/index.ts b/lexicons/aws/src/index.ts index 487058405a..93f69e9ef0 100644 --- a/lexicons/aws/src/index.ts +++ b/lexicons/aws/src/index.ts @@ -145,6 +145,7 @@ export { MicrovmApp, MICROVM_LIMITS, AgentCoreAgent, agentCoreDefaultEndpointArn, OrganizationRoot, GovernanceFoundation, RegionRestriction, OrganizationTrail, + MonitoringStack, } from "./composites/index"; export type { LambdaFunctionProps, LambdaApiProps, ScheduledLambdaProps, @@ -156,6 +157,7 @@ export type { MicrovmAppProps, MicrovmAppResult, MicrovmAppBuildConnectorProps, MicrovmMemoryMiB, AgentCoreAgentProps, AgentCoreAgentResult, OrganizationRootProps, GovernanceFoundationProps, RegionRestrictionProps, OrganizationTrailProps, + MonitoringStackProps, MonitoringMetricSpec, } from "./composites/index"; // Code generation pipeline diff --git a/test/floci-gaps.md b/test/floci-gaps.md index aba9a9f1e2..f1743af504 100644 --- a/test/floci-gaps.md +++ b/test/floci-gaps.md @@ -399,3 +399,67 @@ a reconcile regenerates the networking estate but cannot carry the AKS cluster; the authored cluster source stays as-is. `test/azure-cc-e2e.sh` asserts exactly that split. Entry stands until the listing includes modeled providers. + +## 11. `AWS::CloudWatch::Dashboard` deploys via CloudFormation but the CloudWatch API refuses to read it back + +**Status:** confirmed 2026-08-24 against `floci/floci:latest`, unfiled. Found +while building the `MonitoringStack` composite (chant#1139). + +``` +$ aws cloudformation deploy --stack-name monitoring-stack-check --template-file template.json +Successfully created/updated stack - monitoring-stack-check + +$ aws cloudformation describe-stack-resources --stack-name monitoring-stack-check \ + --query 'StackResources[?ResourceType==`AWS::CloudWatch::Dashboard`]' +[{"LogicalResourceId":"monitoringDashboard","PhysicalResourceId":"monitoringDashboard-28e4fce3", + "ResourceType":"AWS::CloudWatch::Dashboard","ResourceStatus":"CREATE_COMPLETE"}] + +$ aws cloudwatch list-dashboards +An error occurred (UnsupportedOperation) when calling the ListDashboards operation: +Operation ListDashboards is not supported by CloudWatch JSON. + +$ aws cloudwatch get-dashboard --dashboard-name floci-check-dashboard +An error occurred (UnsupportedOperation) when calling the GetDashboard operation: +Operation GetDashboard is not supported by CloudWatch JSON. +``` + +CloudFormation's own resource-type handler accepts the create and reports +`CREATE_COMPLETE` (`monitoring` shows `"running"` on `/_localstack/health`), +but the CloudWatch service surface behind that same emulator has no +dashboard-reading operations at all — not partial, absent. + +**Effect on chant:** synthesis and `cfn-deploy` for a `CwDashboard` resource +(via the new `MonitoringStack` composite or a bare declaration) both work +end-to-end on Floci, so the write half of the composite's Floci coverage is +real. What cannot be exercised here is reading the dashboard back — a +`lifecycle snapshot --deep`/live-diff over a Dashboard degrades exactly like +entry 1's Cloud Control gap, for the same underlying reason (the emulator +reports a service `running` that only partially implements it). The +`AWS::CloudWatch::Alarm` half has no such gap — `describe-alarms` returns the +alarm with every property (`Namespace`, `MetricName`, `Dimensions`, +`Threshold`, `ComparisonOperator`, `EvaluationPeriods`) round-tripped exactly. + +**Priority:** low. Real AWS serves both operations; the composite's write +path (the half a `cfn-deploy` estate depends on) is unaffected. + +## 12. `AWS::CloudWatch::Dashboard`'s physical id ignores the declared `DashboardName` + +**Status:** confirmed 2026-08-24 against `floci/floci:latest`, unfiled. Same +deploy as entry 11. + +The CloudFormation schema for `AWS::CloudWatch::Dashboard` declares +`DashboardName` as `createOnly` and its `primaryIdentifier` — on real AWS the +physical resource id is the dashboard name you set (or a generated one only +when you omit it). Here, with `DashboardName: "floci-check-dashboard"` +explicit in the deployed template, `describe-stack-resources` still reports +`PhysicalResourceId: "monitoringDashboard-28e4fce3"` — the logical id plus a +random suffix, not the name that was declared. + +**Effect on chant:** nothing observed yet — nothing in the composite or its +tests depends on the dashboard's physical id, and the property itself +(`DashboardName`) round-trips correctly in the template and (per entry 11) is +unreadable back from the API either way. Filed because a future live-read or +drift check over dashboards would trip on it: the physical id a `describe- +stack-resources` call reports would not match the name an estate declared. + +**Priority:** low, same reasoning as entry 11.