Skip to content

feat(web-function): manage .local companion log group - #105

Merged
ncipollina merged 10 commits into
mainfrom
feat/web-function-companion-log-groups
Oct 27, 2026
Merged

ncipollina merged 10 commits into
mainfrom
feat/web-function-companion-log-groups

Conversation

@ncipollina

Copy link
Copy Markdown
Contributor

Summary

Manage the Web Function .local companion log group with finite retention, so a Web Function never leaves an unbounded, untagged log group behind. Synthesizing a Web Function with WebFunctionLogs.Create() now produces two AWS::Logs::LogGroup resources — the centralized group and its home-Region .local companion — both with finite retention and the same removal policy:

  • Create(retention, removalPolicy, companionRetention = 1–7 days) — creates the centralized group and the .local companion; the companion has an independently configurable finite retention (default 3 days) and inherits the removal policy.
  • Use(logGroup, companion?) — the documented, tested path to bring your own centralized group and optional companion and avoid an unmanaged companion; grants are scoped to the companion and, when the role is managed by the construct, include logs:CreateLogGroup on the home-Region companion ARN.
  • ServiceDefault() — documented behavior unchanged (no construct-managed groups).

The capability is tracked by GitHub issue #104 and implements approved design revision 5 (docs/designs/lambda-web-functions-integration.md). It ships as a new 2.6.0-preview.N from main; stable 2.6.0 is not published.

Changes

  • WebFunctionLogs API (src/LayeredCraft.Cdk.Constructs/Models/WebFunctionLogs.cs): adds optional companionRetention to Create and an optional companion to Use, with token-safe validation that a caller-supplied companion is named {centralized}.local.
  • WebFunctionConstruct (src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs): creates the companion LogGroup for the Create path, exposes LocalLogGroup, wires the revision to depend on both groups, and emits the unmanaged-companion warning W1 (@layeredcraft/cdk-constructs:webFunctionUnmanagedCompanionLogGroup) when Use is called without a companion.
  • WebFunctionEndpointConstruct: emits the remote-companion warning W2 (@layeredcraft/cdk-constructs:webFunctionRemoteCompanionLogGroups) for PerRegion/MultiRegion endpoints, where the companion log group is not created by this stack; the companion write grant uses a region-scoped ARN in that case.
  • Docs: design revision 5 (§8.3 / §17), docs/constructs/web-function.md, docs/testing/index.md, CLAUDE.md, and CHANGELOG.md updated (two groups per Create, AlreadyExists remedy, recompile note, CDK floor unchanged).

Validation

Local (final release candidate)

  • dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release → succeeded, 0 warnings, 0 errors (net8.0–net11.0).
  • dotnet test LayeredCraft.Cdk.Constructs.slnx -c Release --no-build → 2380 total, 0 failed, 0 skipped (595 tests × 4 TFMs).
  • Golden templates: only Web Function goldens changed — web-function-cloudfront-oac.json, web-function-default.json, web-function-externally-managed.json, web-function-invoke-grants.json, web-function-multi-endpoint.json, web-function-owned-bucket.json (+10 lines each) and the new web-function-use-log-group.json (+44 lines). web-function-application-managed.json and every non-Web-Function golden (cognito×3, dynamodb×4, lambda×6, static-site×4) are unchanged → existing constructs show zero diff.

Live AWS sandbox (bead cdkc-18e.18.4)

Validated in authorized sandbox wft7d (account 403542860824, us-east-1), namespace lccdk-wf-sandbox; all stacks CREATE_COMPLETE; nextjs/aspnetcore/blazor/uselogs/usecompanion functions Active.

Check Result
A – Managed groups & retention PASS — 10/10 groups present pre- and post-traffic with configured retentions (14/3, 14/3, 30/1, 7/none, 14/3); CFN-owned groups match the app stack; managed companions appear in the revision DependsOn.
B – Log delivery PASS — all 10 groups held recent events (logs filter-log-events, 4h lookback); no extra sandbox group; both centralized and .local delivered. verify-log-groups.sh --expect-delivery → PASS=31 FAIL=0 SKIP=0 BLOCKED=0.
C – Use-mode grants (G1/G2) PASS — real IAM inline policy confirmed logs:CreateLogStream/PutLogEvents on .../uselogs:* and .../uselogs.local:log-stream:*, plus logs:CreateLogGroup on .../uselogs.local (no :* suffix, G2 ARN form confirmed); group not part of the app stack's AWS::Logs::LogGroup resources.
D – Supplied companion PASS — Use with an explicit companion yields G1-only grants (no CreateLogGroup), no duplicate group, supplied retentions preserved, delivery confirmed.
E – Warnings PASS/SKIP — W1 emitted (captured from cdk.out metadata); W2 SKIPPED (no PerRegion/MultiRegion endpoint deployed in the sandbox).
F – AlreadyExists collision OPTIONAL/SKIP — remedy documented.
G – Teardown PASS — all 3 stacks destroyed/absent; buckets emptied and deleted; service-created .../uselogs.local removed by exact name; post-destroy and delayed (180s) rechecks show no recreation.

Offline suites: run-scenarios 110 pass, run-smoke-scenarios 44 pass. A sandbox-harness state-isolation defect (SANDBOX_STATE_DIR) was fixed; no production-construct defect was found.

Breaking Changes

None at the source level. The added optional parameters on WebFunctionLogs.Create/Use (design decision D2) are source-compatible. They are binary-incompatible with 2.6.0-preview.27: assemblies compiled against the prior preview must be recompiled, otherwise a MissingMethodException can occur. No released version is claimed by this PR. The CDK floor is unchanged at Amazon.CDK.Lib >= 2.274.0.

Related Issues

Notes for Reviewers

  • Design revision 5 decisions D1–D10 in docs/designs/lambda-web-functions-integration.md are the authoritative record; warnings are referenced verbatim as W1/W2.
  • Out of scope for [Feature]: Manage the Web Function .local companion log group with finite retention #104: non-home-Region log-group creation, changing the centralized default name/retention, log-level/metric/subscription helpers, adoption/import machinery, and any Sharedale changes.

ncipollina and others added 8 commits October 26, 2026 12:16
…groups

Record design revision 5 for managed .local companion log groups (#104):
WebFunctionLogs Create/Use API, LocalLogGroup, THREE_DAYS companion default,
explicit revision dependencies, per-resource-type execution-role grants with a
synthesis-time Lazy Region (order-independent AddEndpoint), W1/W2 warnings,
AlreadyExists guidance, tests, and sandbox check 3.9.

Beads: close cdkc-18e.18.1; refine cdkc-18e.18.2-.18.4.

Refs #104

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Implement design revision 5 for issue #104:
- WebFunctionLogs.Create gains companionRetention (default THREE_DAYS); Use gains an optional companion log group with literal-name validation.
- WebFunctionConstruct creates the .local companion log group (child LocalLogGroup), exposes ILogGroup? LocalLogGroup, and adds revision dependencies on managed log groups.
- Companion IAM grants G1 (always) and G2 (conditional) with synthesis-deferred Region widening; warnings W1/W2.
- Testing assertions ShouldHaveLogGroup/ShouldHaveCompanionLogGroup/ShouldHaveRevisionDependingOnLogGroups; 36 new tests; regenerated Web Function golden templates.

Bead: cdkc-18e.18.2
Apply the independent-review corrections to the revision-5 companion (.local)
log group implementation:

- D1: rename the new log-group assertion to ShouldHaveWebFunctionLogGroup to
  avoid a CS0121 clash with the published
  LambdaFunctionConstructAssertions.ShouldHaveLogGroup; restore the extension
  call in TestingHelpersTests and add consumer/negative coverage.
- D2: add meaningful positive+negative tests for all three new assertions.
- D3: make the W2 warning token-safe (name substituted with "this endpoint"
  when unresolved); add a tokenized-endpoint regression test.
- D4: use the uncached Lazy.UncachedString/IStringProducer so G1/G2 reflect
  the final endpoint set even when the role policy is resolved before
  AddEndpoint; add early-resolution ordering tests (P11b).
- D5: validate the supplied companion name against the underlying CfnLogGroup
  (via the construct default child) for owned groups, keeping token tolerance.
- D6: assert Properties.ServiceConfig.TelemetryConfig in the ServiceDefault
  test instead of the vacuous Properties.TelemetryConfig.
- Strengthen IAM/dependency tests to exact actions and full ARN structure;
  assert the real revision DependsOn (T8), add a cross-stack owned-group case
  (T8b) and warning acknowledgement tests.
- Record design errata A/B/C in the revision-5 design document (no revision 6).

Validation: Release build 0 warnings/0 errors on net8.0-net11.0; 590 tests,
0 failed, 0 skipped on each TFM; coverage line 94.46% / branch 86.28%; Web
Function and existing-construct golden templates unchanged.
F1: add explicit companion-name validation regressions (owned owned/imported/tokenized/unnamed).
F2: assert specific exception types and messages in companion assertion helper tests.
F3: pin the exact consumer-stack revision dependency set in the cross-stack case.
F4: make W2 endpoint label readable and token-safe (no doubled 'Endpoint' prefix).
F5: correct revision-5 Erratum B wording for Create/Use companion-name derivation.
…ion (#104)

Add a read-only verify-log-groups.sh that asserts the companion .local
log-group acceptance criteria (existence, retention, delivery, and no
unexpected groups) against the live CloudWatch Logs API, sourcing the
expected groups/retentions from a new LogGroupExpectations app output.

Add two Use-mode logging functions (caller-owned custom centralised group
with a supplied execution role, and a supplied companion group) and a
non-default Create() companion retention on Blazor so both the managed and
Use-mode paths are exercised.

Teach destroy.sh to remove the one Lambda-created .local companion that
CloudFormation does not own, by exact sandbox-namespaced name only, and
extend the offline aws/cdk stubs plus lifecycle scenarios to cover it.
@github-actions github-actions Bot added the type: feat New feature label Oct 27, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T11:55:25.653367Z 1154205 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 586486d1e1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread samples/web-functions/sandbox/README.md Outdated
Comment on lines +143 to +146
# 5b. Verify the companion ".local" log groups and their retention (read-only). Run once right after
# deploy (pre-traffic) and again with --expect-delivery after real requests.
SANDBOX_ALLOW_AWS=1 ./verify-log-groups.sh
SANDBOX_ALLOW_AWS=1 ./verify-log-groups.sh --expect-delivery

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invoke the Use-mode workloads before checking log delivery

On a fresh sandbox, this documented sequence does not generate traffic for the new UseLogs and UseCompanion functions: smoke.sh still only reads endpoint URLs and sends requests for Next.js, ASP.NET Core, and Blazor. Consequently, verify-log-groups.sh --expect-delivery, which requires events in all ten groups, fails for the new workloads, and the service-created UseLogs companion may not even exist. Add signed requests to both new endpoints to the smoke harness (and expose their URLs), or include an explicit invocation step before this delivery check.

Useful? React with 👍 / 👎.

Comment on lines +1039 to +1046
foreach (var property in template.GetProperty("Resources").EnumerateObject())
{
if (property.Value.TryGetProperty("Type", out var resourceType)
&& resourceType.GetString() == type)
{
result.Add(new KeyValuePair<string, JsonElement>(property.Name, property.Value));
}
}
Expose UseLogsEndpointUrl/UseCompanionEndpointUrl outputs from the sandbox
app stack and add an explicit signed-invoke step (5c) to the run
instructions, so the delivery check (--expect-delivery) has recent events
for the Use-mode groups and the service-created uselogs.local companion
exists before it runs.

Addresses the Codex review finding on samples/web-functions/sandbox/README.md
(smoke.sh only drives the Next.js/ASP.NET Core/Blazor endpoints).

#104
@ncipollina

Copy link
Copy Markdown
Contributor Author

@codex review

Follow-up review requested for commit c93c42a, which addresses the single Codex finding from the initial review (P2 on samples/web-functions/sandbox/README.md):

  • Exposed UseLogsEndpointUrl and UseCompanionEndpointUrl outputs from samples/web-functions/sandbox/AppStack.cs (mirroring the other endpoints' .Url).
  • Added an explicit signed-invoke step (5c) to the run sequence in samples/web-functions/sandbox/README.md: it assumes the sandbox CallerRole via aws sts assume-role and sends SigV4-signed requests to both Use-mode endpoint URLs before the --expect-delivery check, so both Use-mode groups hold recent events and the service-created uselogs.local companion exists.

Please confirm this resolves the finding and does not introduce regressions or leave the original finding unresolved.

(The separate github-code-quality "missed opportunity to use Where" note in WebFunctionCompanionLogGroupTests.cs was reviewed and deemed a non-actionable style nit.)

Offline sandbox suites remain green after the change: run-scenarios 110 passed/0 failed, run-smoke-scenarios 44 passed/0 failed; the sandbox app stack builds with 0 warnings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c93c42a4af

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread samples/web-functions/sandbox/README.md Outdated
Comment on lines +162 to +163
curl -sS -o /dev/null --aws-sigv4 "aws:amz:${SANDBOX_REGION}:lambda" \
--user "${AK}:${SK}" -H "x-amz-security-token: ${TOKEN}" "$(output "$KEY")" || true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the required payload-hash header in signed requests

The new invocation step omits x-amz-content-sha256: UNSIGNED-PAYLOAD, which docs/constructs/web-function.md documents as required for IAM-authenticated requests and the existing signer in smoke.sh explicitly supplies. Replaying this new command against a local HTTP listener with curl 8.5.0 confirmed that --aws-sigv4 does not automatically emit that header for service lambda. Consequently, these requests are rejected before reaching either workload, leaving the original fresh-sandbox delivery failure unresolved despite exposing the endpoint URLs. Add the payload-hash header to both requests; discarding their responses currently conceals the authentication failure.

Useful? React with 👍 / 👎.

…ash header

The new 5c invocation step in the sandbox README omitted the
x-amz-content-sha256: UNSIGNED-PAYLOAD header that IAM-authenticated Web
Function endpoints require (documented in docs/constructs/web-function.md
and explicitly supplied by smoke.sh's signer). Without it the signed
requests are rejected before reaching the workloads, leaving the original
fresh-sandbox delivery failure unresolved. Add the header to both requests
and surface the HTTP status instead of silently discarding the response.

Addresses review finding on #104.
@ncipollina

Copy link
Copy Markdown
Contributor Author

@codex review

Follow-up review requested for commit 1154205, which addresses the new P2 finding (missing payload-hash header) from the previous review of c93c42a:

  • Verified the claim and corrected it: docs/constructs/web-function.md:592 requires x-amz-content-sha256: UNSIGNED-PAYLOAD for IAM-authenticated requests, and the working signer in smoke.sh (line 278) explicitly supplies it.
  • Added -H "x-amz-content-sha256: UNSIGNED-PAYLOAD" to both Use-mode requests in step 5c of samples/web-functions/sandbox/README.md.
  • Also stopped silently discarding the responses: each request now prints its HTTP status (invoked <KEY> (<URL>) -> HTTP <code>) so authentication failures are visible.

Please confirm this resolves the finding and that no remaining actionable findings or regressions exist on this commit.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 1154205f1a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ncipollina
ncipollina merged commit 63db9b1 into main Oct 27, 2026
9 checks passed
@ncipollina
ncipollina deleted the feat/web-function-companion-log-groups branch October 27, 2026 11:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Manage the Web Function .local companion log group with finite retention

1 participant