mirror of
https://github.com/floci-io/floci.git
synced 2026-12-06 11:38:06 -05:00
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.
This commit is contained in:
1 parent
a3da2a3767
commit
22b0627245
88 files changed
+19188
-101
No files matched your search
@@ -51,6 +51,49 @@ just test-python
|
||||
|
||||
AWS credentials are always `test` / `test` / `us-east-1`.
|
||||
|
||||
## Opt-in metric filter replay against AWS
|
||||
|
||||
`tests/metric_filter_replay.py` is a standalone script, not a test: pytest does
|
||||
not collect it, and `tests/test_metric_filter_replay.py` checks its logic offline
|
||||
with the network blocked. It does not change `conftest.py`, and `FLOCI_TARGET=aws`
|
||||
does not select real AWS.
|
||||
|
||||
From the repository root, with the declared requirements installed:
|
||||
|
||||
```bash
|
||||
python -m pytest compatibility-tests/sdk-test-python/tests/test_metric_filter_replay.py
|
||||
|
||||
# Against a local Floci
|
||||
python compatibility-tests/sdk-test-python/tests/metric_filter_replay.py \
|
||||
--endpoint http://127.0.0.1:4566 --region eu-west-1 \
|
||||
--timeout 30 --stable-seconds 2 --poll-interval 1
|
||||
```
|
||||
|
||||
Real AWS mode requires all three safety arguments. **It creates billable
|
||||
CloudWatch metrics and a tagged log group, and metric series cannot be deleted**;
|
||||
they remain until AWS ages them out.
|
||||
|
||||
```bash
|
||||
python compatibility-tests/sdk-test-python/tests/metric_filter_replay.py \
|
||||
--aws --profile YOUR_DISPOSABLE_TEST_PROFILE --region eu-west-1 \
|
||||
--ack-live-writes I_ACCEPT_AWS_WRITES
|
||||
```
|
||||
|
||||
Only commercial AWS regions are accepted, the clients pin the official regional
|
||||
endpoints, and the group is deleted in `finally` only after its ownership tag is
|
||||
verified. A cleanup failure exits nonzero and prints the group name. Credentials,
|
||||
account ids, profile names and raw service errors are never printed.
|
||||
|
||||
The expected values come from `tests/fixtures/metric-filter-publishing-aws.json`,
|
||||
a byte-identical copy of the root fixture
|
||||
`src/test/resources/cloudwatchlogs/metric-filter-publishing-aws.json`; the root
|
||||
`CloudWatchLogsMetricFilterFixturePackagingTest` fails when either SDK module copy
|
||||
drifts. The replay ingests each scenario into its own backdated minute, runs the
|
||||
quiet-default scenario last with no later ingestion, and accepts a result only
|
||||
after every expected series, absent series and the idle minute after the quiet one
|
||||
have stayed stable for a full window (AWS defaults: 240 second deadline, 30 second
|
||||
window). Output is JSON lines of observations, not a regenerated fixture.
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"verification": "Verified on Live AWS",
|
||||
"observedDate": "2026-09-16",
|
||||
"region": "eu-west-1",
|
||||
"awsCliVersion": "2.36.45",
|
||||
"description": "Normalized observations from isolated synthetic PutMetricFilter/PutLogEvents/GetMetricStatistics probes. Values are independent AWS results, not emulator-generated expectations.",
|
||||
"period": 60,
|
||||
"observedThrough": "2026-09-16T09:06:51Z",
|
||||
"metricDefaults": {
|
||||
"filterPattern": "ERROR",
|
||||
"metricValue": "3",
|
||||
"defaultValue": 7,
|
||||
"cases": [
|
||||
{
|
||||
"name": "mixed events in one batch",
|
||||
"batches": [["ERROR", "INFO", "ERROR"]],
|
||||
"expected": {"Sum": 13, "SampleCount": 3, "Minimum": 3, "Maximum": 7}
|
||||
},
|
||||
{
|
||||
"name": "hit then miss in separate batches",
|
||||
"batches": [["ERROR"], ["INFO"]],
|
||||
"expected": {"Sum": 10, "SampleCount": 2, "Minimum": 3, "Maximum": 7}
|
||||
},
|
||||
{
|
||||
"name": "miss then hit in separate batches",
|
||||
"batches": [["INFO"], ["ERROR"]],
|
||||
"expected": {"Sum": 10, "SampleCount": 2, "Minimum": 3, "Maximum": 7}
|
||||
}
|
||||
],
|
||||
"qualification": "Each case used one isolated event-time minute. Results converged through repeated reads over approximately 107 seconds. No minute-wide suppression or default deduplication was observed."
|
||||
},
|
||||
"extraction": {
|
||||
"filterPattern": "{ $.probe = \"value\" || $.value = * }",
|
||||
"metricValue": "$.value",
|
||||
"defaultValue": 7,
|
||||
"cases": [
|
||||
{
|
||||
"name": "matching event with missing value",
|
||||
"message": {"probe": "value", "case": "missing"},
|
||||
"expected": {"Sum": 7, "SampleCount": 1}
|
||||
},
|
||||
{
|
||||
"name": "matching event with null value",
|
||||
"message": {"probe": "value", "value": null, "case": "null"},
|
||||
"expected": {"Sum": 7, "SampleCount": 1}
|
||||
},
|
||||
{
|
||||
"name": "matching event with nonnumeric string",
|
||||
"message": {"probe": "value", "value": "not-a-number", "case": "nonnumeric"},
|
||||
"expected": {"datapoints": []}
|
||||
},
|
||||
{
|
||||
"name": "matching numeric control",
|
||||
"message": {"probe": "value", "value": 3, "case": "numeric-control"},
|
||||
"expected": {"Sum": 3, "SampleCount": 1}
|
||||
}
|
||||
],
|
||||
"qualification": "Cases occupied distinct event-time minutes. Matching did not depend on the value field being present. The numeric control succeeded; negative results remained absent through the completed observation window."
|
||||
},
|
||||
"ordinaryDimensions": {
|
||||
"filterPattern": "{ $.probe = \"dimension\" || $.a = * || $.b = * }",
|
||||
"metricValue": "1",
|
||||
"dimensions": {"A": "$.a", "B": "$.b"},
|
||||
"messages": [
|
||||
{"probe": "dimension", "a": "alpha", "b": "beta"},
|
||||
{"probe": "dimension", "a": "alpha"},
|
||||
{"probe": "dimension", "b": "beta"},
|
||||
{"probe": "dimension"}
|
||||
],
|
||||
"expectedSeries": [
|
||||
{"dimensions": {"A": "alpha", "B": "beta"}, "Sum": 1, "SampleCount": 1},
|
||||
{"dimensions": {}, "Sum": 3, "SampleCount": 3}
|
||||
],
|
||||
"absentSeries": [
|
||||
{"dimensions": {"A": "alpha"}},
|
||||
{"dimensions": {"B": "beta"}}
|
||||
],
|
||||
"qualification": "No default configured. All events occupied one minute. ListMetrics confirmed complete and dimensionless series, not partial sets. Null or empty dimension values were not measured."
|
||||
},
|
||||
"systemDimensions": {
|
||||
"filterPattern": "ERROR",
|
||||
"metricValue": "3",
|
||||
"defaultValue": 7,
|
||||
"messages": ["ERROR", "INFO"],
|
||||
"accountTransformerPolicyCount": 0,
|
||||
"groupTransformerConfig": [],
|
||||
"cases": [
|
||||
{
|
||||
"emitSystemFieldDimensions": ["@aws.account"],
|
||||
"expectedSeries": [
|
||||
{"dimensions": {"@aws.account": "<CALLER_ACCOUNT>"}, "Sum": 3, "SampleCount": 1},
|
||||
{"dimensions": {}, "Sum": 7, "SampleCount": 1}
|
||||
]
|
||||
},
|
||||
{
|
||||
"emitSystemFieldDimensions": ["@aws.region"],
|
||||
"expectedSeries": [
|
||||
{"dimensions": {"@aws.region": "eu-west-1"}, "Sum": 3, "SampleCount": 1},
|
||||
{"dimensions": {}, "Sum": 7, "SampleCount": 1}
|
||||
]
|
||||
},
|
||||
{
|
||||
"emitSystemFieldDimensions": ["@aws.account", "@aws.region"],
|
||||
"expectedSeries": [
|
||||
{"dimensions": {"@aws.account": "<CALLER_ACCOUNT>", "@aws.region": "eu-west-1"}, "Sum": 3, "SampleCount": 1},
|
||||
{"dimensions": {}, "Sum": 7, "SampleCount": 1}
|
||||
]
|
||||
}
|
||||
],
|
||||
"qualification": "Regular noncentralized group. Matching events receive requested system dimensions; pattern-nonmatch defaults are dimensionless. This does not measure extraction-fallback defaults or centralized source provenance."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Opt-in stateful replay. Import and normal pytest execution never contact AWS."""
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager, ExitStack
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
import boto3
|
||||
import botocore.session
|
||||
from botocore.config import Config
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parent / "fixtures/metric-filter-publishing-aws.json"
|
||||
OWNER_TAG = "floci-metric-replay"
|
||||
|
||||
|
||||
class ReplayError(Exception):
|
||||
"""Only fixed, sanitized diagnostics belong in this exception."""
|
||||
|
||||
|
||||
class SafeParser(argparse.ArgumentParser):
|
||||
def error(self, message):
|
||||
self.exit(2, "Invalid replay arguments; use --help. No replay was started.\n")
|
||||
|
||||
|
||||
def parse_args(argv=None):
|
||||
parser = SafeParser(description=__doc__)
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument("--aws", action="store_true", help="Write to real commercial-partition AWS")
|
||||
mode.add_argument("--endpoint", help="Explicit loopback Floci endpoint, with dummy credentials")
|
||||
parser.add_argument("--profile")
|
||||
parser.add_argument("--region")
|
||||
parser.add_argument("--ack-live-writes", choices=["I_ACCEPT_AWS_WRITES"])
|
||||
parser.add_argument("--timeout", type=float, default=240, help="Maximum observation seconds")
|
||||
parser.add_argument("--stable-seconds", type=float, default=30, help="Complete stable observation window")
|
||||
parser.add_argument("--poll-interval", type=float, default=5)
|
||||
args = parser.parse_args(argv)
|
||||
if args.aws:
|
||||
if not args.profile or not args.region or not args.ack_live_writes:
|
||||
parser.error("AWS requires explicit profile, region and acknowledgement")
|
||||
if args.region not in botocore.session.get_session().get_available_regions("logs", partition_name="aws"):
|
||||
parser.error("Only known commercial AWS regions are supported")
|
||||
if args.stable_seconds < 30 or args.timeout < 120:
|
||||
parser.error("AWS observations require at least 120 seconds and a 30-second stable window")
|
||||
else:
|
||||
try:
|
||||
endpoint = urlsplit(args.endpoint)
|
||||
except ValueError:
|
||||
parser.error("Invalid local endpoint")
|
||||
if (endpoint.scheme not in ("http", "https")
|
||||
or endpoint.hostname not in ("localhost", "127.0.0.1", "::1")
|
||||
or endpoint.username or endpoint.password or endpoint.path not in ("", "/")
|
||||
or endpoint.query or endpoint.fragment or args.profile or args.ack_live_writes):
|
||||
parser.error("Local mode requires a credential-free loopback endpoint")
|
||||
args.region = args.region or "eu-west-1"
|
||||
if not (0 < args.poll_interval <= args.stable_seconds < args.timeout <= 900):
|
||||
parser.error("Invalid bounded observation window")
|
||||
return args
|
||||
|
||||
|
||||
def clients(args, session=None):
|
||||
session = session or (boto3.Session(profile_name=args.profile, region_name=args.region)
|
||||
if args.aws else boto3.Session(region_name=args.region))
|
||||
config = Config(ignore_configured_endpoint_urls=True, connect_timeout=5, read_timeout=15,
|
||||
retries={"max_attempts": 2, "mode": "standard"})
|
||||
result = []
|
||||
for service, endpoint_prefix in (("logs", "logs"), ("cloudwatch", "monitoring"), ("sts", "sts")):
|
||||
endpoint = f"https://{endpoint_prefix}.{args.region}.amazonaws.com" if args.aws else args.endpoint
|
||||
credentials = {} if args.aws else {
|
||||
"aws_access_key_id": "test", "aws_secret_access_key": "test", "aws_session_token": ""}
|
||||
result.append(session.client(service, region_name=args.region, endpoint_url=endpoint,
|
||||
config=config, **credentials))
|
||||
return tuple(result)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def owned_group(logs, group, token):
|
||||
# A rejected create must never cause deletion of an existing resource.
|
||||
logs.create_log_group(logGroupName=group, tags={OWNER_TAG: token})
|
||||
try:
|
||||
if logs.list_tags_log_group(logGroupName=group).get("tags", {}).get(OWNER_TAG) != token:
|
||||
raise ReplayError("created group ownership could not be verified")
|
||||
logs.create_log_stream(logGroupName=group, logStreamName="probe")
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
if logs.list_tags_log_group(logGroupName=group).get("tags", {}).get(OWNER_TAG) != token:
|
||||
raise ReplayError("cleanup refused: group ownership could not be verified")
|
||||
logs.delete_log_group(logGroupName=group)
|
||||
except Exception:
|
||||
raise ReplayError("cleanup failed or refused; inspect the owned run's log group") from None
|
||||
|
||||
|
||||
def await_stable(read, timeout, stable_seconds, interval, monotonic=None, sleep=None):
|
||||
monotonic, sleep = monotonic or time.monotonic, sleep or time.sleep
|
||||
deadline = monotonic() + timeout
|
||||
stable_since = None
|
||||
while True:
|
||||
complete = read()
|
||||
now = monotonic()
|
||||
if now > deadline:
|
||||
raise ReplayError("observations did not converge within the bounded window")
|
||||
stable_since = (now if stable_since is None else stable_since) if complete else None
|
||||
if stable_since is not None and now - stable_since >= stable_seconds:
|
||||
return
|
||||
if now >= deadline:
|
||||
raise ReplayError("observations did not converge within the bounded window")
|
||||
sleep(min(interval, deadline - now))
|
||||
|
||||
|
||||
def safe_error(error):
|
||||
return str(error) if isinstance(error, ReplayError) else type(error).__name__
|
||||
|
||||
|
||||
def scenarios(fixture, start, account, region):
|
||||
cases = []
|
||||
|
||||
def add(name, definition, batches, expected, system_fields=None):
|
||||
cases.append({"name": name, "minute": start + timedelta(minutes=len(cases)),
|
||||
"definition": definition, "batches": batches,
|
||||
"expected": expected, "system_fields": system_fields or []})
|
||||
|
||||
defaults = fixture["metricDefaults"]
|
||||
for i, scenario in enumerate(defaults["cases"]):
|
||||
add(f"default-{i}", defaults, scenario["batches"], [{"dimensions": {}, **scenario["expected"]}])
|
||||
extraction = fixture["extraction"]
|
||||
for i, scenario in enumerate(extraction["cases"]):
|
||||
add(f"extraction-{i}", extraction, [[json.dumps(scenario["message"])]],
|
||||
[{"dimensions": {}, **scenario["expected"]}])
|
||||
ordinary = fixture["ordinaryDimensions"]
|
||||
add("dimensions", ordinary, [[json.dumps(m) for m in ordinary["messages"]]],
|
||||
ordinary["expectedSeries"] + [{"datapoints": [], **s} for s in ordinary["absentSeries"]])
|
||||
system = fixture["systemDimensions"]
|
||||
for i, scenario in enumerate(system["cases"]):
|
||||
expected = []
|
||||
for series in scenario["expectedSeries"]:
|
||||
dimensions = {k: account if k == "@aws.account" else region for k in series["dimensions"]}
|
||||
expected.append({**series, "dimensions": dimensions})
|
||||
add(f"system-{i}", system, [system["messages"]], expected, scenario["emitSystemFieldDimensions"])
|
||||
add("quiet", defaults, [["INFO", "INFO", "INFO"]], [{"dimensions": {}, "Sum": 21, "SampleCount": 3}])
|
||||
return cases
|
||||
|
||||
|
||||
def observe(cw, namespace, cases):
|
||||
complete = True
|
||||
observations = []
|
||||
for case in cases:
|
||||
for expected in case["expected"]:
|
||||
dimensions = expected["dimensions"]
|
||||
stats = [name for name in ("Sum", "SampleCount", "Minimum", "Maximum") if name in expected]
|
||||
points = cw.get_metric_statistics(Namespace=namespace, MetricName=case["name"],
|
||||
Dimensions=[{"Name": k, "Value": v} for k, v in dimensions.items()],
|
||||
StartTime=case["minute"], EndTime=case["minute"] + timedelta(minutes=1),
|
||||
Period=60, Statistics=stats or ["Sum", "SampleCount"])["Datapoints"]
|
||||
present = "Sum" in expected
|
||||
matches = len(points) == (1 if present else 0)
|
||||
if matches and present:
|
||||
matches = (points[0]["Timestamp"] == case["minute"]
|
||||
and all(points[0].get(stat) == expected[stat] for stat in stats))
|
||||
complete = complete and matches
|
||||
observations.append({"case": case["name"], "timestamp": case["minute"].isoformat(),
|
||||
"dimensions": {k: "<CALLER_ACCOUNT>" if k == "@aws.account" else v for k, v in dimensions.items()},
|
||||
"datapoints": [{"timestamp": p["Timestamp"].isoformat(),
|
||||
**{s: p[s] for s in ("Sum", "SampleCount", "Minimum", "Maximum") if s in p}}
|
||||
for p in points]})
|
||||
return complete, observations
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = parse_args(argv)
|
||||
token = uuid.uuid4().hex
|
||||
group = "/floci-metric-replay/" + token
|
||||
namespace = "FlociMetricReplay/" + token
|
||||
print(json.dumps({"mode": "AWS LIVE WRITES" if args.aws else "local Floci only",
|
||||
"group": group, "namespace": namespace,
|
||||
"warning": "Metric series cannot be deleted. They remain until the service ages them out."}))
|
||||
try:
|
||||
with ExitStack() as stack:
|
||||
logs, cw, sts = clients(args)
|
||||
for client in (logs, cw, sts):
|
||||
stack.callback(client.close)
|
||||
account = sts.get_caller_identity()["Account"]
|
||||
start = datetime.now(timezone.utc).replace(second=0, microsecond=0) - timedelta(minutes=40)
|
||||
cases = scenarios(json.loads(FIXTURE.read_text()), start, account, args.region)
|
||||
observations = []
|
||||
with owned_group(logs, group, token):
|
||||
for case in cases:
|
||||
definition = case["definition"]
|
||||
transformation = {"metricNamespace": namespace, "metricName": case["name"],
|
||||
"metricValue": definition["metricValue"], "unit": "Count"}
|
||||
for field in ("defaultValue", "dimensions"):
|
||||
if field in definition:
|
||||
transformation[field] = definition[field]
|
||||
request = {"logGroupName": group, "filterName": "probe",
|
||||
"filterPattern": definition["filterPattern"],
|
||||
"metricTransformations": [transformation]}
|
||||
if case["system_fields"]:
|
||||
request["emitSystemFieldDimensions"] = case["system_fields"]
|
||||
logs.put_metric_filter(**request)
|
||||
for batch in case["batches"]:
|
||||
response = logs.put_log_events(logGroupName=group, logStreamName="probe",
|
||||
logEvents=[{"timestamp": int(case["minute"].timestamp() * 1000) + i, "message": message}
|
||||
for i, message in enumerate(batch)])
|
||||
if response.get("rejectedLogEventsInfo"):
|
||||
raise ReplayError("replay log events were rejected")
|
||||
|
||||
checks = cases + [{"name": "quiet", "minute": cases[-1]["minute"] + timedelta(minutes=1),
|
||||
"expected": [{"dimensions": {}, "datapoints": []}]}]
|
||||
|
||||
def read():
|
||||
nonlocal observations
|
||||
complete, observations = observe(cw, namespace, checks)
|
||||
return complete
|
||||
|
||||
try:
|
||||
await_stable(read, args.timeout, args.stable_seconds, args.poll_interval)
|
||||
finally:
|
||||
print(json.dumps({"observations": observations}))
|
||||
print(json.dumps({"result": "converged", "cleanup": "owned log group deleted",
|
||||
"qualification": "Local results are not live AWS verification."
|
||||
if not args.aws else "Only these replayed scenarios were observed."}))
|
||||
return 0
|
||||
except Exception as error:
|
||||
print(json.dumps({"result": "failed", "error": safe_error(error),
|
||||
"cleanup_hint": group}), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Offline checks only: no AWS clients or sockets are opened by these tests."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import socket
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"metric_filter_replay", Path(__file__).resolve().parent / "metric_filter_replay.py")
|
||||
replay = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(replay)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_network(monkeypatch):
|
||||
def reject(*args, **kwargs):
|
||||
pytest.fail("offline replay checks must not open a network connection")
|
||||
monkeypatch.setattr(socket.socket, "connect", reject)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def orchestration(monkeypatch):
|
||||
logs, cw, sts = Mock(), Mock(), Mock()
|
||||
state = SimpleNamespace(metric=None, ingestions=[], observations=0, now=0)
|
||||
sts.get_caller_identity.return_value = {"Account": "123456789012"}
|
||||
logs.list_tags_log_group.side_effect = lambda **kwargs: {"tags": logs.create_log_group.call_args.kwargs["tags"]}
|
||||
def put_filter(**request):
|
||||
state.metric = request["metricTransformations"][0]["metricName"]
|
||||
def put_events(**request):
|
||||
state.ingestions.append((state.metric, request["logEvents"]))
|
||||
return {}
|
||||
def sleep(seconds):
|
||||
state.now += seconds
|
||||
logs.put_metric_filter.side_effect = put_filter
|
||||
logs.put_log_events.side_effect = put_events
|
||||
monkeypatch.setattr(replay, "clients", lambda args: (logs, cw, sts))
|
||||
monkeypatch.setattr(replay.time, "monotonic", lambda: state.now)
|
||||
monkeypatch.setattr(replay.time, "sleep", sleep)
|
||||
return state
|
||||
|
||||
|
||||
def test_fixture_is_packaged_beside_the_module_not_in_a_repository_ancestor():
|
||||
expected = Path(__file__).resolve().parent / "fixtures/metric-filter-publishing-aws.json"
|
||||
assert replay.FIXTURE == expected
|
||||
assert replay.FIXTURE.is_file()
|
||||
|
||||
|
||||
def test_quiet_ingestion_is_last_through_successful_stable_observation(monkeypatch, orchestration):
|
||||
state = orchestration
|
||||
def observe(*args):
|
||||
state.observations += 1
|
||||
assert state.ingestions[-1][0] == "quiet", "later traffic could flush a broken quiet publisher"
|
||||
assert [e["message"] for e in state.ingestions[-1][1]] == ["INFO", "INFO", "INFO"]
|
||||
assert sum(metric == "quiet" for metric, _ in state.ingestions) == 1
|
||||
return state.observations > 1, []
|
||||
monkeypatch.setattr(replay, "observe", observe)
|
||||
assert replay.main(["--endpoint", "http://127.0.0.1:4566", "--timeout", "10",
|
||||
"--stable-seconds", "2", "--poll-interval", "1"]) == 0
|
||||
assert state.observations >= 4
|
||||
assert state.ingestions[-1][0] == "quiet"
|
||||
|
||||
|
||||
def test_idle_window_is_distinct_unwritten_and_checked_through_convergence(monkeypatch, orchestration):
|
||||
state = orchestration
|
||||
def observe(cw, namespace, cases):
|
||||
state.observations += 1
|
||||
quiet = [case for case in cases if case["name"] == "quiet"]
|
||||
assert len(quiet) == 2, "check the positive quiet minute and a separate empty minute"
|
||||
populated, idle = sorted(quiet, key=lambda case: case["minute"])
|
||||
assert idle["minute"] == populated["minute"] + timedelta(minutes=1)
|
||||
assert populated["expected"][0]["Sum"] == 21
|
||||
assert idle["expected"] == [{"dimensions": {}, "datapoints": []}]
|
||||
start = int(idle["minute"].timestamp() * 1000)
|
||||
assert all(not start <= event["timestamp"] < start + 60_000
|
||||
for _, events in state.ingestions for event in events)
|
||||
return state.observations > 1, []
|
||||
monkeypatch.setattr(replay, "observe", observe)
|
||||
assert replay.main(["--endpoint", "http://127.0.0.1:4566", "--timeout", "10",
|
||||
"--stable-seconds", "2", "--poll-interval", "1"]) == 0
|
||||
assert state.observations >= 4
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [
|
||||
[], ["--aws"], ["--aws", "--profile", "synthetic", "--region", "eu-west-1"],
|
||||
["--aws", "--ack-live-writes", "I_ACCEPT_AWS_WRITES", "--region", "eu-west-1"],
|
||||
["--aws", "--ack-live-writes", "I_ACCEPT_AWS_WRITES", "--profile", "synthetic"],
|
||||
["--endpoint", "https://logs.eu-west-1.amazonaws.com"],
|
||||
["--endpoint", "http://127.0.0.1:4566@evil.example"],
|
||||
["--endpoint", "http://localhost:4566", "--profile", "synthetic"],
|
||||
["--endpoint", "http://127.0.0.1:4566/path"],
|
||||
["--endpoint", "http://[malformed-private-endpoint"],
|
||||
# GovCloud and China are real botocore Regions but not the commercial partition the endpoints pin.
|
||||
["--aws", "--profile", "synthetic", "--region", "us-gov-west-1", "--ack-live-writes", "I_ACCEPT_AWS_WRITES"],
|
||||
["--aws", "--profile", "synthetic", "--region", "cn-north-1", "--ack-live-writes", "I_ACCEPT_AWS_WRITES"],
|
||||
])
|
||||
def test_rejects_unguarded_or_remote_writes_before_creating_clients(args):
|
||||
with pytest.raises(SystemExit):
|
||||
replay.parse_args(args)
|
||||
|
||||
|
||||
def test_live_clients_pin_official_endpoints_despite_environment(monkeypatch):
|
||||
monkeypatch.setenv("AWS_ENDPOINT_URL", "https://untrusted.invalid")
|
||||
monkeypatch.setenv("AWS_ENDPOINT_URL_CLOUDWATCH_LOGS", "https://untrusted.invalid")
|
||||
args = replay.parse_args(["--aws", "--profile", "synthetic", "--region", "eu-west-1",
|
||||
"--ack-live-writes", "I_ACCEPT_AWS_WRITES"])
|
||||
session = Mock()
|
||||
replay.clients(args, session)
|
||||
calls = {call.args[0]: call.kwargs for call in session.client.call_args_list}
|
||||
assert calls["logs"]["endpoint_url"] == "https://logs.eu-west-1.amazonaws.com"
|
||||
assert calls["cloudwatch"]["endpoint_url"] == "https://monitoring.eu-west-1.amazonaws.com"
|
||||
assert calls["sts"]["endpoint_url"] == "https://sts.eu-west-1.amazonaws.com"
|
||||
assert all(c["config"].ignore_configured_endpoint_urls for c in calls.values())
|
||||
|
||||
|
||||
def test_local_clients_use_only_explicit_loopback_and_dummy_credentials():
|
||||
args = replay.parse_args(["--endpoint", "http://127.0.0.1:18084"])
|
||||
session = Mock()
|
||||
replay.clients(args, session)
|
||||
for call in session.client.call_args_list:
|
||||
assert call.kwargs["endpoint_url"] == "http://127.0.0.1:18084"
|
||||
assert call.kwargs["aws_access_key_id"] == "test"
|
||||
assert call.kwargs["aws_secret_access_key"] == "test"
|
||||
assert call.kwargs["aws_session_token"] == ""
|
||||
|
||||
|
||||
def test_owned_group_is_verified_again_before_cleanup_even_when_body_fails():
|
||||
logs = Mock()
|
||||
logs.list_tags_log_group.return_value = {"tags": {"floci-metric-replay": "token"}}
|
||||
with pytest.raises(RuntimeError, match="body"):
|
||||
with replay.owned_group(logs, "/owned", "token"):
|
||||
raise RuntimeError("body")
|
||||
assert logs.list_tags_log_group.call_count == 2
|
||||
logs.delete_log_group.assert_called_once_with(logGroupName="/owned")
|
||||
|
||||
|
||||
def test_cleanup_does_not_delete_a_group_whose_ownership_changed():
|
||||
logs = Mock()
|
||||
logs.list_tags_log_group.side_effect = [
|
||||
{"tags": {"floci-metric-replay": "token"}}, {"tags": {"floci-metric-replay": "someone-else"}}]
|
||||
with pytest.raises(replay.ReplayError, match="cleanup"):
|
||||
with replay.owned_group(logs, "/owned", "token"):
|
||||
pass
|
||||
logs.delete_log_group.assert_not_called()
|
||||
|
||||
|
||||
def test_failed_create_never_deletes_an_existing_group():
|
||||
logs = Mock()
|
||||
logs.create_log_group.side_effect = RuntimeError("private endpoint and credentials")
|
||||
with pytest.raises(RuntimeError, match="private endpoint"):
|
||||
with replay.owned_group(logs, "/owned", "token"):
|
||||
pytest.fail("must not start replay")
|
||||
logs.delete_log_group.assert_not_called()
|
||||
|
||||
|
||||
def test_cleanup_failure_is_visible_and_does_not_leak_service_exception():
|
||||
logs = Mock()
|
||||
logs.list_tags_log_group.return_value = {"tags": {"floci-metric-replay": "token"}}
|
||||
logs.delete_log_group.side_effect = RuntimeError("private account credentials")
|
||||
with pytest.raises(replay.ReplayError, match="cleanup failed") as error:
|
||||
with replay.owned_group(logs, "/owned", "token"):
|
||||
raise ValueError("private profile")
|
||||
assert "private" not in str(error.value)
|
||||
|
||||
|
||||
def test_polling_requires_positive_controls_then_a_stable_complete_window():
|
||||
clock = SimpleNamespace(now=0)
|
||||
def sleep(seconds):
|
||||
clock.now += seconds
|
||||
observations = iter([False, False, True, False, True, True, True])
|
||||
reads = []
|
||||
def read():
|
||||
reads.append(clock.now)
|
||||
return next(observations)
|
||||
replay.await_stable(read, timeout=20, stable_seconds=2, interval=1,
|
||||
monotonic=lambda: clock.now, sleep=sleep)
|
||||
assert reads == [0, 1, 2, 3, 4, 5, 6]
|
||||
|
||||
|
||||
def test_never_converging_observations_fail_at_a_bounded_deadline():
|
||||
clock = SimpleNamespace(now=0)
|
||||
def sleep(seconds):
|
||||
clock.now += seconds
|
||||
with pytest.raises(replay.ReplayError, match="converge"):
|
||||
replay.await_stable(lambda: False, timeout=3, stable_seconds=2, interval=1,
|
||||
monotonic=lambda: clock.now, sleep=sleep)
|
||||
assert clock.now == 3
|
||||
|
||||
|
||||
def test_slow_final_read_cannot_succeed_after_the_deadline():
|
||||
clock = SimpleNamespace(now=0)
|
||||
def sleep(seconds):
|
||||
clock.now += seconds
|
||||
def read():
|
||||
if clock.now:
|
||||
clock.now += 3
|
||||
return True
|
||||
with pytest.raises(replay.ReplayError, match="converge"):
|
||||
replay.await_stable(read, timeout=3, stable_seconds=2, interval=1,
|
||||
monotonic=lambda: clock.now, sleep=sleep)
|
||||
|
||||
|
||||
def test_invalid_argument_output_never_echoes_private_values(capsys):
|
||||
with pytest.raises(SystemExit):
|
||||
replay.parse_args(["--unknown", "private-profile-name"])
|
||||
assert "private-profile-name" not in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_error_output_is_sanitized():
|
||||
assert replay.safe_error(RuntimeError("profile secret account 123456789012")) == "RuntimeError"
|
||||
assert replay.safe_error(replay.ReplayError("cleanup failed")) == "cleanup failed"
|
||||
|
||||
|
||||
def test_scenarios_use_immutable_recorded_values_and_distinct_event_minutes():
|
||||
fixture = json.loads(replay.FIXTURE.read_text())
|
||||
before = json.dumps(fixture)
|
||||
cases = replay.scenarios(fixture, datetime(2026, 9, 16, tzinfo=timezone.utc), "123456789012", "eu-west-1")
|
||||
by_name = {case["name"]: case for case in cases}
|
||||
assert len(cases) == 12
|
||||
assert len({case["minute"] for case in cases}) == 12
|
||||
assert [by_name[name]["expected"][0]["Sum"] for name in ("default-0", "default-1", "default-2", "quiet")] == [13, 10, 10, 21]
|
||||
assert by_name["extraction-0"]["expected"][0]["Sum"] == 7
|
||||
assert by_name["extraction-1"]["expected"][0]["Sum"] == 7
|
||||
assert by_name["extraction-2"]["expected"][0] == {"dimensions": {}, "datapoints": []}
|
||||
assert by_name["extraction-3"]["expected"][0]["Sum"] == 3
|
||||
assert len(by_name["dimensions"]["expected"]) == 4
|
||||
assert json.dumps(fixture) == before
|
||||
|
||||
|
||||
def test_observation_rejects_wrong_timestamps_partial_counts_and_sanitizes_account():
|
||||
minute = datetime(2026, 9, 16, tzinfo=timezone.utc)
|
||||
case = {"name": "system", "minute": minute, "expected": [
|
||||
{"dimensions": {"@aws.account": "123456789012"}, "Sum": 3, "SampleCount": 1}]}
|
||||
cw = Mock()
|
||||
point = {"Timestamp": minute, "Sum": 3.0, "SampleCount": 1.0, "Unit": "Count"}
|
||||
cw.get_metric_statistics.return_value = {"Datapoints": [point]}
|
||||
complete, observations = replay.observe(cw, "namespace", [case])
|
||||
assert complete
|
||||
assert "123456789012" not in json.dumps(observations)
|
||||
assert "<CALLER_ACCOUNT>" in json.dumps(observations)
|
||||
point["SampleCount"] = 2
|
||||
assert not replay.observe(cw, "namespace", [case])[0]
|
||||
point["SampleCount"] = 1
|
||||
point["Timestamp"] = datetime(2026, 9, 16, 0, 1, tzinfo=timezone.utc)
|
||||
assert not replay.observe(cw, "namespace", [case])[0]
|
||||
Reference in new issue
Block a user