Files
floci/tools/docs/test_service_inventory.py
T
Mario Toffia 22b0627245 test(compat): assert recorded metric filter publishing through the SDK modules (#3809)
* feat(logs): add metric filters with per-event metric publication

Implements PutMetricFilter, DescribeMetricFilters, DeleteMetricFilter and
TestMetricFilter on the CloudWatch Logs JSON 1.1 handler, backed by a filter
pattern engine for term, space-delimited and JSON patterns. The grammar is
checked against 148 TestMetricFilter cases recorded from AWS, kept as
fixtures under src/test/resources/cloudwatchlogs and recaptured with the
opt-in script under tools/aws-capture/cloudwatchlogs.

Validation follows the observed AWS wire behavior: the five regex-bearing
filters per log group quota is shared with subscription filters through one
canonical backend monitor, a filter pattern may hold at most two regular
expressions, defaultValue must be a JSON number, DescribeMetricFilters
requires metricName and metricNamespace together in both directions, and
TestMetricFilter reports one-based event numbers with an empty public
extractedValues map for JSON patterns.

Ingested events publish samples into CloudWatch Metrics per event at the
event timestamp: matching events contribute the extracted or literal value,
non-matching events contribute defaultValue, dimensions are all-or-none, and
system dimensions only attach to matching events. Failed publications are
retried from a bounded queue of 10,000 samples with stable publication ids.

Resettable gains beforeReset and afterReset default hooks so the metric
filter publisher can pause and drain before a state reset wipes storage and
resume afterwards. EmulatorInfoController.performReset is serialized and
calls the hooks around the existing container teardown and storage wipe,
running afterReset in a finally block so a failed wipe cannot leave a
publisher paused. The GetMetricStatistics and GetMetricData Query responses
now carry the CloudWatch namespace so both read paths return the same
samples.

* feat(cloudformation): provision AWS::Logs::MetricFilter

Adds LogsMetricFilterCfnProvisioner for creates, in-place updates, name
changes and deletes. Ref and PhysicalResourceId are the filter name alone,
as observed on AWS; the log group is kept as private resource metadata.
A replacement deletes the old filter before creating the new one, matching
the DELETE then CREATE event order AWS emits, and a failed replacement
recreates the previous definition on rollback.

Every mutation records an APPLIED, NOT_APPLIED or UNKNOWN outcome under the
service lock so a failed or ambiguous call can never authorize deleting or
overwriting a filter the stack does not own. Ownership that cannot be proven
is resolved conservatively before the next mutation.

The engine gains three small provisioner hooks that this type needs and
others may reuse:

- ProvisionContext carries a progress consumer so a provisioner can emit
  the intermediate DELETE_IN_PROGRESS and DELETE_COMPLETE events of a
  delete-first replacement while provision is still running.
- rollbackUpdate(resource, progress) lets a provisioner restore its own
  previous state during UPDATE_ROLLBACK and report the steps as events.
- hasPendingRollbackCleanup and retainsFailedUpdateState let a provisioner
  tell the engine that an UPDATE_FAILED resource still holds its own
  rollback snapshot, so the engine neither restores the previous resource
  over it nor refuses a later DeleteStack. Both default to false; only this
  provisioner overrides them.

The type is listed in supported-resource-types.tsv, the generated resource
table and CfnProvisionerFixture, with unit, integration, storage reload and
SDK coverage.

* docs(logs): document metric filters and the AWS verification record

Describes the metric filter operations, publication semantics and
CloudFormation support in docs/services/cloudwatch.md and adds
cloudwatch-metric-filters-verification.md, the record of what was observed
on AWS in eu-west-1, with which tools, and where each recorded fixture came
from. Registers the handler and the verification page with the docs tooling
and teaches the service inventory test to count facet pages.

* feat(logs): publish metric filter samples off the PutLogEvents thread

PutLogEvents evaluated each filter and wrote one CloudWatch Metrics sample
per filter and event on the request thread while holding the filter-store
monitor, up to a million writes for a maximal request, so ingestion latency
depended on the Metrics sink and every PutMetricFilter waited behind the
whole batch.

The request thread now only evaluates the group's filters as they are at
ingestion and hands the resulting immutable samples, with their stable
publication ids, to a bounded queue of 100,000 samples. The existing single
worker drains it and writes one sample per monitor acquisition, so a
PutMetricFilter or a reset waits for at most one write. A batch that does
not fit the queue is written inline on the request thread rather than
dropped. Failed writes still land in the 10,000 sample retry map with the
same ids and cadence as before.

Reset pauses the worker, discards queued and failed samples and bumps a
generation counter so a batch taken before the reset is never written into
the wiped store. Shutdown drains the queue before storage shuts down and
clears the retry map only after the worker has terminated. Samples ingested
while Metrics is disabled are discarded at startup.

Integration and SDK tests poll for the sample, as they would against AWS.

* test(compat): assert recorded metric filter publishing through the SDK modules

Extends the Java compatibility module with the publishing scenarios recorded
from AWS: mixed defaults and quiet traffic, extraction and ordinary dimension
series, system dimensions on matches only, and a Sum alarm driven by quiet
defaults. Each series is read through the SDK's CloudWatch JSON protocol and
again as a signed legacy Query request, so GetMetricStatistics and
GetMetricData agree on every sample, timestamp, unit and dimension set.

Expected values come from module-local copies of the root fixture
metric-filter-publishing-aws.json. MetricFilterFixturePackagingTest checks
the Java copy loads from the classpath and the root
CloudWatchLogsMetricFilterFixturePackagingTest fails when either SDK module
copy drifts from the root file.

The Python module gains tests/metric_filter_replay.py, an opt-in replay of
the same scenarios against a Floci endpoint or, with explicit profile,
region and write acknowledgement, against AWS. Its logic is covered offline
by tests/test_metric_filter_replay.py with the network blocked. Both module
Dockerfiles are unchanged: the Java image already runs the whole suite and
the Python image already copies tests/.

* test(compat): assert every recorded statistic and poll for published samples

The SDK publishing assertions compared only Sum and SampleCount although the
AWS fixture also records Minimum and Maximum for the default-value scenarios.
Both the SDK JSON reads and the signed legacy Query reads now assert every
statistic the fixture carries, on GetMetricStatistics and GetMetricData.

Publication now happens shortly after PutLogEvents returns, so present series
are polled and absent series are asserted only after a later positive control
of the same filter is visible, which the publisher's ordering guarantees. The
read window ends at second 59 so a sample stamped on the following minute is
never in scope.

The live replay's Region check names the commercial partition explicitly.
botocore already defaults get_available_regions to partition_name="aws", so
GovCloud and China Regions were rejected before; the offline test now pins it.

* test(compat): keep the metric filter SDK test on the Java 17 API of the compat image

List.getLast() is Java 21; the sdk-test-java image compiles with Temurin 17.
2026-09-17 13:53:35 -04:00

321 lines
13 KiB
Python

"""Tests for service_inventory.
Every test here pins a parser trap that was found by hand-checking the real sources,
and that would otherwise have made this tool produce a *tenth* wrong number in a repo
that already had nine. They are written against synthetic sources so they keep failing
for the right reason when the real files change.
Run with: pytest tools/docs -q (or: make docs-test)
"""
from __future__ import annotations
from datetime import date
import pytest
import service_inventory as si
# --------------------------------------------------------------------------- #
# Key normalisation
# --------------------------------------------------------------------------- #
def test_key_normalises_across_naming_conventions():
# The same service, spelled three ways by three sources.
assert si.key("bcmDataExports") == si.key("bcm-data-exports") == si.key("bcmdataexports")
def test_key_does_not_collide_across_distinct_services():
assert si.key("rds") != si.key("rds-data")
# --------------------------------------------------------------------------- #
# Descriptor parsing
# --------------------------------------------------------------------------- #
SIMPLE = '''
descriptor("ssm", "ssm", config.services().ssm().enabled(), true,
"ssm", storageMode(...), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonSSM."), Set.of("ssm"), Set.of(), Set.of()),
'''
def test_parses_key_config_key_and_status_flag():
[d] = si.parse_descriptors(SIMPLE)
assert d["external_key"] == "ssm"
assert d["config_key"] == "ssm"
assert d["toggles"] == ["ssm"]
assert d["in_status"] is True
def test_conjunction_toggle_wrapping_onto_a_continuation_line():
# rds-data and redshift-data wrap because their enabled expression is a conjunction.
# A line-oriented parser reads `true` off the *first* line, which for these two is
# the configKey's line, and gets both the toggles and includeInStatus wrong.
src = '''
descriptor("rds-data", "rds-data",
config.services().rds().enabled() && config.services().rdsData().enabled(), false,
null, null, 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("rds-data"), Set.of(), Set.of(RdsDataController.class)),
'''
[d] = si.parse_descriptors(src)
assert d["external_key"] == "rds-data"
assert d["toggles"] == ["rds", "rdsData"]
assert d["in_status"] is False
def test_status_flag_is_read_from_the_fourth_argument_not_the_first_true():
# `includeInStatus=false` on a descriptor whose second line contains other literals.
src = '''
descriptor("sts", "iam", config.services().iam().enabled(), false,
null, null, 5000L, AwsNamespaces.STS, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("sts"), Set.of(), Set.of()),
'''
assert si.parse_descriptors(src)[0]["in_status"] is False
def test_nested_commas_do_not_split_an_argument():
args = si.split_top_level_args('f("a", Set.of("b", "c"), true)', 1)
assert args == ['"a"', 'Set.of("b", "c")', "true"]
def test_unbalanced_parens_raise_rather_than_returning_a_short_list():
with pytest.raises(ValueError, match="unbalanced"):
si.split_top_level_args('f("a", "b"', 1)
def test_non_literal_external_key_raises():
# check_service_matrix.py catches this case by counting call sites; here it must
# fail loudly rather than silently dropping a service from every count.
with pytest.raises(ValueError, match="not a plain string literal"):
si.parse_descriptors("descriptor(KEY, \"ssm\", true, true, ...)")
# --------------------------------------------------------------------------- #
# Config accessors
# --------------------------------------------------------------------------- #
def test_config_accessors_exclude_docker_network_and_include_non_service_configs():
# DuckConfig does not end in ServiceConfig, so a `*ServiceConfig` pattern misses it
# and under-counts by one. dockerNetwork() returns Optional<String> and must not
# be counted at all.
src = """
interface ServicesConfig {
Optional<String> dockerNetwork();
SsmServiceConfig ssm();
SqsServiceConfig sqs();
DuckConfig duck();
}
"""
assert si.parse_config_accessors(src) == ["duck", "sqs", "ssm"]
def test_missing_services_config_interface_raises():
with pytest.raises(ValueError, match="ServicesConfig not found"):
si.parse_config_accessors("interface Unrelated { }")
# --------------------------------------------------------------------------- #
# Matrix rows
# --------------------------------------------------------------------------- #
MATRIX = f"""{si.csm.MATRIX_HEADING}
| Service | Endpoint | Protocol | Supported operations |
|---|---|---|---|
| [DynamoDB](dynamodb.md) | `POST /` | JSON 1.1 | 28 |
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` | JSON 1.1 | 4 |
| [IoT Core](iot.md) | `/things` | REST JSON | 40 |
| [IoT Data](iot.md) | `/topics` | REST JSON | 5 |
| [S3](s3.md) | `/{{bucket}}` | REST XML | 58 |
{si.csm.MATRIX_END_HEADING}
"""
def test_facet_rows_are_detected_by_duplicate_slug_not_by_anchor():
# IoT Core and IoT Data both link plain `iot.md` with no anchor at all. An
# anchor-based rule finds only the DynamoDB pair and over-counts pages by one.
rows = si.parse_matrix_rows(MATRIX)
assert len(rows) == 5
assert {r["slug"] for r in rows} == {"dynamodb", "iot", "s3"}
assert rows[3]["anchor"] is None
def test_rows_outside_the_matrix_headings_are_ignored():
src = f"| [Elsewhere](elsewhere.md) | x |\n\n{MATRIX}"
assert all(r["slug"] != "elsewhere" for r in si.parse_matrix_rows(src))
# --------------------------------------------------------------------------- #
# README
# --------------------------------------------------------------------------- #
def test_category_names_do_not_split_inside_parentheses():
# "IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM)" is one service name.
# Splitting on every comma turns it into four, three of which ("OIDC", "SCIM)")
# are not service names and inflate the count.
src = (
"| Category | Services |\n|---|---|\n"
"| Identity | IAM, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), KMS |\n"
"\nFor operation-level compatibility, see the Services Overview.\n"
)
assert si.parse_readme_category_names(src) == [
"IAM",
"IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM)",
"KMS",
]
def test_detail_rows_take_the_first_cell_only():
src = (
"| Service | How it works | Notable features |\n|---|---|---|\n"
"| SQS | In-process | Standard and FIFO queues, DLQ |\n"
"</details>\n"
)
assert si.parse_readme_detail_rows(src) == ["SQS"]
# --------------------------------------------------------------------------- #
# Reconciliation
# --------------------------------------------------------------------------- #
def _data(**overrides) -> dict:
base = {
"descriptors": [
{"external_key": "iam", "config_key": "iam", "toggles": ["iam"], "in_status": True},
{"external_key": "sts", "config_key": "iam", "toggles": ["iam"], "in_status": False},
{"external_key": "s3", "config_key": "s3", "toggles": ["s3"], "in_status": True},
],
"config_accessors": ["iam", "s3", "duck"],
"yaml_keys": ["iam", "s3", "duck"],
"yaml_enabled": ["iam", "s3"],
"packages": ["iam", "s3"],
"matrix_rows": [
{"label": "IAM", "slug": "iam", "anchor": None},
{"label": "AWS Sign-In", "slug": "iam", "anchor": "signin"},
{"label": "S3", "slug": "s3", "anchor": None},
],
"doc_pages": ["iam", "s3"],
"readme_categories": ["IAM", "S3"],
"readme_details": ["S3"],
"action_tables": ["s3"],
"aliases": {"sts": "iam"},
"facet_pages": [],
"deferred": [],
}
base.update(overrides)
return base
def test_shared_toggle_is_reported_with_every_descriptor_it_gates():
r = si.reconcile(_data())
assert r["catalog"]["shared_toggles"] == {"iam": ["iam", "sts"]}
assert r["counts"]["catalog_toggles"] == 2
def test_facet_descriptor_is_the_non_owner_of_a_shared_page():
r = si.reconcile(_data())
assert r["catalog"]["facet_descriptors"] == ["sts"]
assert r["counts"]["catalog_distinct_products"] == 2
def test_non_aws_entries_are_subtracted_from_the_aws_key_count():
r = si.reconcile(_data())
assert r["config"]["non_aws"] == ["duck"]
assert r["counts"]["yaml_aws_keys"] == 2
def test_config_and_yaml_agree_after_normalisation():
r = si.reconcile(_data(config_accessors=["rdsData"], yaml_keys=["rds-data"]))
assert r["config"]["accessor_only"] == []
assert r["config"]["yaml_only"] == []
def test_unregistered_package_is_reported_when_not_noted():
r = si.reconcile(_data(packages=["iam", "s3", "newthing"]))
assert r["packages"]["unregistered"] == ["newthing"]
def test_noted_package_is_not_reported_as_unregistered():
si.PACKAGE_NOTES["temporary"] = "test fixture"
try:
r = si.reconcile(_data(packages=["iam", "s3", "temporary"]))
assert r["packages"]["unregistered"] == []
assert "temporary" in r["packages"]["noted"]
finally:
del si.PACKAGE_NOTES["temporary"]
def test_facet_row_missing_from_readme_is_separated_from_a_real_gap():
# "AWS Sign-In" shares iam.md, so its absence from the README is by design.
# A non-facet row missing from the README is a genuine finding.
r = si.reconcile(_data(readme_categories=["IAM"]))
assert r["readme"]["missing_from_categories"] == ["S3"]
assert r["readme"]["missing_facet_rows"] == ["AWS Sign-In"]
def test_readme_alias_covers_several_matrix_rows_at_once():
si.README_NAME_ALIASES["Identity"] = ["IAM", "AWS Sign-In"]
try:
r = si.reconcile(_data(readme_categories=["Identity", "S3"]))
assert r["readme"]["unmatched_category_names"] == []
assert r["readme"]["missing_facet_rows"] == []
finally:
del si.README_NAME_ALIASES["Identity"]
def test_readme_name_matching_no_row_is_reported_rather_than_dropped():
r = si.reconcile(_data(readme_categories=["IAM", "S3", "Imaginary Service"]))
assert r["readme"]["unmatched_category_names"] == ["Imaginary Service"]
def test_deferral_within_the_warning_window_is_flagged():
deferred = [{"key": "x", "reason": "r", "by": "2026-09-15"}]
r = si.reconcile(_data(deferred=deferred), today=date(2026, 9, 14))
assert r["docs"]["deferred_expiring"] == deferred
def test_deferral_beyond_the_warning_window_is_not_flagged():
deferred = [{"key": "x", "reason": "r", "by": "2027-01-01"}]
r = si.reconcile(_data(deferred=deferred), today=date(2026, 9, 14))
assert r["docs"]["deferred_expiring"] == []
def test_row_exempt_facet_pages_are_counted_without_requiring_a_matrix_row():
r = si.reconcile(_data(doc_pages=["iam", "s3", "iam-verification"],
facet_pages=["iam-verification"]))
assert r["counts"]["matrix_pages"] == 2
assert r["counts"]["doc_pages"] == 3
assert r["docs"]["pages_without_row"] == []
assert r["docs"]["rows_without_page"] == []
def test_facet_exemption_does_not_hide_an_unregistered_page():
r = si.reconcile(_data(doc_pages=["iam", "s3", "iam-verification", "unregistered"],
facet_pages=["iam-verification"]))
assert r["docs"]["pages_without_row"] == ["unregistered"]
# --------------------------------------------------------------------------- #
# End to end, against the real repo
# --------------------------------------------------------------------------- #
def test_real_sources_parse_and_render():
data = si.collect(si._repo_root())
result = si.reconcile(data)
counts = result["counts"]
# Not pinned to exact values: they move every time a service lands. What must hold
# is that every source parsed to something plausible and the two gated equalities
# this tool reports as green really are green.
assert all(v > 50 for v in counts.values())
assert counts["matrix_pages"] == len(set(data["doc_pages"]) - set(data["facet_pages"]))
assert counts["config_accessors"] == counts["yaml_keys"]
assert result["docs"]["pages_without_row"] == []
assert result["docs"]["rows_without_page"] == []
assert result["packages"]["unregistered"] == []
assert "THE ANSWER" in si.render(result)
def test_report_never_suggests_publishing_a_count():
# The hard rule the tool exists to protect, asserted rather than trusted to prose.
text = si.render(si.reconcile(si.collect(si._repo_root())))
assert "Never write any of them into README.md or docs/" in text