Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): add patch, session, and opsitem tables to aws ssm (#119541)

Tom Owers0ac71762cb58
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 558c83587faa..0fad9194d5e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1330,20 +1330,20 @@ Note: The official SDK model was compared with ListStateMachines, ListExecutions
## AWS Systems Manager — **thin**
-Today (10): `association_execution_targets`, `association_executions`, `associations`, `compliance_items`, `documents`, `inventory`, `inventory_entries`, `managed_instances`, `patch_baselines`, `resource_compliance_summaries`
+Today (15): `association_execution_targets`, `association_executions`, `associations`, `compliance_items`, `documents`, `instance_patch_states`, `instance_patches`, `inventory`, `inventory_entries`, `managed_instances`, `ops_item_events`, `ops_items`, `patch_baselines`, `resource_compliance_summaries`, `sessions`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/ssm/2014-11-06/service-2.json>
- [x] `Documents (ListDocuments, POST /)` — resolve association document names to document types, owners, versions, and supported platforms (high)
- [x] `Inventory entries (ListInventoryEntries, POST /)` — analyze installed applications, services, and other inventory beyond the imported AWS:InstanceInformation records (high)
- [x] `Compliance items (ListComplianceItems, POST /)` — identify individual noncompliant patches or associations behind resource compliance totals (high)
-- [ ] `Instance patch states (DescribeInstancePatchStates, POST /)` — measure missing patches, failed patches, and patch scan times for each managed node (high)
-- [ ] `Instance patches (DescribeInstancePatches, POST /)` — analyze installed and missing patches by classification, severity, installation date, and node (high)
+- [x] `Instance patch states (DescribeInstancePatchStates, POST /)` — measure missing patches, failed patches, and patch scan times for each managed node (high)
+- [x] `Instance patches (DescribeInstancePatches, POST /)` — analyze installed and missing patches by classification, severity, installation date, and node (high)
- [x] `Association executions and targets (DescribeAssociationExecutions and DescribeAssociationExecutionTargets, POST /)` — measure association execution success and identify failed target nodes over time (high)
- [ ] `Commands and command invocations (ListCommands and ListCommandInvocations, POST /)` — analyze remote command duration, failures, and results for each target node (medium)
- [ ] `Automation executions and steps (DescribeAutomationExecutions and DescribeAutomationStepExecutions, POST /)` — measure automation outcomes and locate slow or failed runbook steps (medium)
-- [ ] `OpsItems and events (DescribeOpsItems and ListOpsItemEvents, POST /)` — track operational issues, priority, resolution times, and changes throughout their lifecycle (medium)
-- [ ] `Sessions (DescribeSessions, POST /)` — audit session activity, operators, target nodes, duration, and termination status (medium)
+- [x] `OpsItems and events (DescribeOpsItems and ListOpsItemEvents, POST /)` — track operational issues, priority, resolution times, and changes throughout their lifecycle (medium)
+- [x] `Sessions (DescribeSessions, POST /)` — audit session activity, operators, target nodes, duration, and termination status (medium)
Note: The official SDK model lists read operations, required inputs, and collection response fields. The inventory table explicitly requests only AWS:InstanceInformation; other inventory types are absent. Inventory, patches, associations, and automation steps need nested requests; sessions retain only the documented recent history. Parameter secrets, access tokens, settings, resource sync configuration, and write operations are excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py
index 85627db2d12e..e98d5df22af8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/aws_systems_manager.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_system
ERROR_MESSAGES,
EXCLUDED_INVENTORY_TYPES,
MISSING_PARENT_ERRORS,
+ SESSION_STATES,
SystemsManagerEndpoint,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -40,6 +41,10 @@ TRANSPORT_RETRY = BoundedRetry(
raise_on_status=False,
)
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+# Inventory type names and OpsItem data keys are dynamic, so retain them in one JSON column.
+_JSON_COLUMNS = frozenset({"Data", "OperationalData"})
+# DescribeInstancePatchStates accepts at most this many nodes in one request.
+_PATCH_STATE_BATCH_SIZE = 50
_PLACEHOLDER_INSTANCE_ID = "i-00000000000000000"
_PLACEHOLDER_UUID = "00000000-0000-0000-0000-000000000000"
@@ -51,6 +56,7 @@ PLACEHOLDER_PARENTS: dict[str, dict[str, Any]] = {
"ComplianceType": "Patch",
},
"inventory": {"Id": _PLACEHOLDER_INSTANCE_ID},
+ "managed_instances": {"InstanceId": _PLACEHOLDER_INSTANCE_ID},
"associations": {"AssociationId": _PLACEHOLDER_UUID},
"association_executions": {"AssociationId": _PLACEHOLDER_UUID, "ExecutionId": _PLACEHOLDER_UUID},
}
@@ -155,6 +161,13 @@ def request_payload(endpoint: SystemsManagerEndpoint, *, probe: bool = False) ->
return payload
+def root_payloads(endpoint: SystemsManagerEndpoint, *, probe: bool = False) -> list[dict[str, Any]]:
+ payload = request_payload(endpoint, probe=probe)
+ if endpoint.operation == "DescribeSessions":
+ return [{**payload, "State": state} for state in SESSION_STATES]
+ return [payload]
+
+
def endpoint_chain(endpoint: SystemsManagerEndpoint) -> list[SystemsManagerEndpoint]:
chain = [endpoint]
while chain[0].parent is not None:
@@ -191,15 +204,31 @@ def child_payloads(
return [{"AssociationId": parent["AssociationId"]}]
if endpoint.operation == "DescribeAssociationExecutionTargets":
return [{"AssociationId": parent["AssociationId"], "ExecutionId": parent["ExecutionId"]}]
+ if endpoint.operation == "DescribeInstancePatchStates":
+ return [{"InstanceIds": [parent["InstanceId"]]}]
+ if endpoint.operation == "DescribeInstancePatches":
+ return [{"InstanceId": parent["InstanceId"]}]
raise ValueError(f"AWS Systems Manager table has no parent mapping: {endpoint.operation}")
+def page_child_payloads(
+ endpoint: SystemsManagerEndpoint, parents: Sequence[dict[str, Any]], inventory_types: Sequence[str]
+) -> list[dict[str, Any]]:
+ payloads = [payload for parent in parents for payload in child_payloads(endpoint, parent, inventory_types)]
+ if endpoint.operation != "DescribeInstancePatchStates":
+ return payloads
+ instance_ids = [instance_id for payload in payloads for instance_id in payload["InstanceIds"]]
+ return [
+ {"InstanceIds": instance_ids[start : start + _PATCH_STATE_BATCH_SIZE]}
+ for start in range(0, len(instance_ids), _PATCH_STATE_BATCH_SIZE)
+ ]
+
+
def _flatten(obj: dict[str, Any], prefix: str = "") -> dict[str, Any]:
row: dict[str, Any] = {}
for key, value in obj.items():
column = prefix + _CAMEL_BOUNDARY.sub("_", key).lower()
- if key == "Data" and not prefix:
- # Inventory type names and content keys are dynamic, so retain them in one JSON column.
+ if key in _JSON_COLUMNS and not prefix:
row[column] = json.dumps(value)
elif isinstance(value, dict):
row.update(_flatten(value, column + "_"))
@@ -222,6 +251,9 @@ def page_rows(
endpoint: SystemsManagerEndpoint, body: dict[str, Any], payload: dict[str, Any], region: str
) -> list[dict[str, Any]]:
items = body.get(endpoint.result_key) or []
+ if endpoint.operation == "DescribeInstancePatches":
+ # Patches do not name the node they belong to.
+ return [{**normalize_row(item, endpoint, region), "instance_id": payload["InstanceId"]} for item in items]
if endpoint.operation != "ListInventoryEntries":
return [normalize_row(item, endpoint, region) for item in items]
capture_time = body.get("CaptureTime")
@@ -269,7 +301,19 @@ class SystemsManagerWalk:
) -> Iterator[tuple[list[dict[str, Any]], SystemsManagerResumeConfig]]:
if any(endpoint.operation == "ListInventoryEntries" for endpoint in self._chain):
self._inventory_types = self._load_inventory_types()
- yield from self._walk(0, request_payload(self._chain[0]), (), state)
+ payloads = root_payloads(self._chain[0])
+ if len(payloads) == 1:
+ yield from self._walk(0, payloads[0], (), state)
+ return
+ # Each root payload is walked like a parent row, so resume state records which one was in progress.
+ key = state.parents[0][1] if state and state.parents else ""
+ inner = dataclasses.replace(state, parents=state.parents[1:]) if state and state.parents else None
+ roots = {json.dumps(payload, sort_keys=True): payload for payload in payloads}
+ keys = list(roots)
+ start = keys.index(key) if key in roots else 0
+ for root_key in keys[start:]:
+ yield from self._walk(0, roots[root_key], ((None, root_key),), inner if root_key == key else None)
+ yield [], SystemsManagerResumeConfig(completed=True)
def _load_inventory_types(self) -> tuple[str, ...]:
names: set[str] = set()
@@ -349,8 +393,9 @@ class SystemsManagerWalk:
next_token = _next_token(body, token)
children = {
json.dumps(child, sort_keys=True): child
- for item in body.get(endpoint.result_key) or []
- for child in child_payloads(child_endpoint, item, self._inventory_types)
+ for child in page_child_payloads(
+ child_endpoint, body.get(endpoint.result_key) or [], self._inventory_types
+ )
}
keys = list(children)
start = keys.index(key) if key in children else 0
@@ -414,7 +459,7 @@ def validate_credentials(
chain = endpoint_chain(endpoint)
operation = chain[0].operation
try:
- body = client.request(operation, request_payload(chain[0], probe=True))
+ body = client.request(operation, root_payloads(chain[0], probe=True)[0])
if endpoint.operation == "ListInventoryEntries":
operation = "GetInventorySchema"
client.request(operation, {"MaxResults": 50})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py
index a28f83d88920..7807f444dbf1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/canonical_descriptions.py
@@ -150,4 +150,93 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"last_execution_date": "Time when the execution last ran on this resource.",
},
},
+ "instance_patch_states": {
+ "description": "Patch compliance state of each managed node, from its most recent patch scan or install operation.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatchStates.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "instance_id": "Identifier of the managed node.",
+ "patch_group": "Patch group the managed node belongs to.",
+ "baseline_id": "Identifier of the patch baseline used for the last patch operation.",
+ "operation": "Type of the last patch operation, Scan or Install.",
+ "operation_start_time": "Time when the last patch operation started.",
+ "operation_end_time": "Time when the last patch operation ended.",
+ "installed_count": "Number of patches from the baseline that are installed.",
+ "installed_other_count": "Number of installed patches that are not in the baseline.",
+ "installed_pending_reboot_count": "Number of patches installed since the last reboot.",
+ "installed_rejected_count": "Number of installed patches that the baseline rejects.",
+ "missing_count": "Number of applicable patches from the baseline that are not installed.",
+ "failed_count": "Number of patches from the baseline that failed to install.",
+ "not_applicable_count": "Number of baseline patches that do not apply to the node.",
+ "critical_non_compliant_count": "Number of missing patches with a critical compliance severity.",
+ "security_non_compliant_count": "Number of missing patches classified as security updates.",
+ "other_non_compliant_count": "Number of missing patches that are not critical or security updates.",
+ "reboot_option": "Reboot behavior requested for the last install operation.",
+ },
+ },
+ "instance_patches": {
+ "description": "Patches on each managed node, with their installation state.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatches.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "instance_id": "Identifier of the managed node.",
+ "title": "Title of the patch.",
+ "kb_id": "Operating system-specific identifier of the patch.",
+ "classification": "Classification of the patch, such as SecurityUpdates or Bugfix.",
+ "severity": "Severity of the patch, such as Critical or Important.",
+ "state": "State of the patch on the node, such as Installed, Missing, or Failed.",
+ "installed_time": "Time when the patch was installed on the node.",
+ "cve_ids": "CVE identifiers that the patch resolves, separated by commas.",
+ },
+ },
+ "sessions": {
+ "description": "Session Manager sessions. Ended sessions are available for 30 days.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeSessions.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "session_id": "Identifier of the session.",
+ "target": "Managed node that the session connects to.",
+ "status": "Status of the session, such as Connected or Terminated.",
+ "start_date": "Time when the session started.",
+ "end_date": "Time when the session ended.",
+ "document_name": "Session document used to start the session.",
+ "owner": "ARN of the user who started the session.",
+ "reason": "Reason given when the session started.",
+ "max_session_duration": "Maximum duration of the session, in minutes.",
+ "access_type": "Access type of the session, Standard or JustInTime.",
+ },
+ },
+ "ops_items": {
+ "description": "OpsCenter OpsItems that track operational issues in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeOpsItems.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "ops_item_id": "Identifier of the OpsItem.",
+ "title": "Title of the OpsItem.",
+ "status": "Status of the OpsItem, such as Open, InProgress, or Resolved.",
+ "priority": "Priority of the OpsItem, from 1 (highest) to 5.",
+ "severity": "Severity of the OpsItem.",
+ "category": "Category of the OpsItem.",
+ "source": "Origin of the OpsItem, such as EC2 or a CloudWatch alarm.",
+ "ops_item_type": "Type of the OpsItem.",
+ "created_by": "ARN of the identity that created the OpsItem.",
+ "created_time": "Time when the OpsItem was created.",
+ "last_modified_time": "Time when the OpsItem was last changed.",
+ "operational_data": "JSON of the operational data keys attached to the OpsItem.",
+ },
+ },
+ "ops_item_events": {
+ "description": "Events that changed OpsItems in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListOpsItemEvents.html",
+ "columns": {
+ "region": "AWS region selected for this source.",
+ "ops_item_id": "Identifier of the OpsItem that the event changed.",
+ "event_id": "Identifier of the event.",
+ "source": "Source of the event.",
+ "detail_type": "Type of the event detail.",
+ "detail": "Detail of the event.",
+ "created_by_arn": "ARN of the identity that created the event.",
+ "created_time": "Time when the event was created.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py
index d1f1f38e7afc..2f41732baf8b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/settings.py
@@ -98,8 +98,59 @@ ENDPOINTS: dict[str, SystemsManagerEndpoint] = {
timestamps=("last_execution_date",),
parent="association_executions",
),
+ "instance_patch_states": SystemsManagerEndpoint(
+ operation="DescribeInstancePatchStates",
+ result_key="InstancePatchStates",
+ primary_key=("region", "instance_id"),
+ description="Patch counts by state, the patch baseline, and the last patch operation for each managed node.",
+ probe_size=10,
+ timestamps=("operation_start_time", "operation_end_time", "last_no_reboot_install_operation_time"),
+ parent="managed_instances",
+ ),
+ "instance_patches": SystemsManagerEndpoint(
+ operation="DescribeInstancePatches",
+ result_key="Patches",
+ primary_key=("region", "instance_id", "kb_id", "title"),
+ description="Installed, missing, and failed patches on each managed node, with classification and severity.",
+ page_size=100,
+ probe_size=10,
+ timestamps=("installed_time",),
+ parent="managed_instances",
+ ),
+ "sessions": SystemsManagerEndpoint(
+ operation="DescribeSessions",
+ result_key="Sessions",
+ primary_key=("region", "session_id"),
+ description="Active Session Manager sessions and sessions that ended in the past 30 days.",
+ page_size=200,
+ timestamps=("start_date", "end_date"),
+ ),
+ "ops_items": SystemsManagerEndpoint(
+ operation="DescribeOpsItems",
+ result_key="OpsItemSummaries",
+ primary_key=("region", "ops_item_id"),
+ description="OpsCenter OpsItems with status, priority, severity, and planned and actual times.",
+ timestamps=(
+ "created_time",
+ "last_modified_time",
+ "actual_start_time",
+ "actual_end_time",
+ "planned_start_time",
+ "planned_end_time",
+ ),
+ ),
+ "ops_item_events": SystemsManagerEndpoint(
+ operation="ListOpsItemEvents",
+ result_key="Summaries",
+ primary_key=("region", "ops_item_id", "event_id"),
+ description="Events that changed OpsItems, with the event source, detail, and creation time.",
+ timestamps=("created_time",),
+ ),
}
+# Ended sessions first, so a session that ends between the two requests cannot appear twice under one key.
+SESSION_STATES = ("History", "Active")
+
# Other tables already sync these inventory types.
EXCLUDED_INVENTORY_TYPES = frozenset({"AWS:InstanceInformation", "AWS:ComplianceItem", "AWS:ComplianceSummary"})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
index 1128930260f4..63ae88b5d938 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/source.py
@@ -111,13 +111,14 @@ class AwsSystemsManagerSource(ResumableSource[AwsSystemsManagerSourceConfig, Sys
name=ExternalDataSourceType.AWSSYSTEMSMANAGER,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AWS Systems Manager",
- caption="""Sync fleet inventory, compliance, associations, documents, and patch baselines from one AWS region.
+ caption="""Sync fleet inventory, compliance, associations, documents, patching, sessions, and OpsItems from one AWS region.
Grant these IAM permissions for the tables you select:
`ssm:DescribeInstanceInformation`, `ssm:GetInventory`, `ssm:GetInventorySchema`, `ssm:ListInventoryEntries`,
`ssm:ListResourceComplianceSummaries`, `ssm:ListComplianceItems`, `ssm:ListAssociations`,
`ssm:DescribeAssociationExecutions`, `ssm:DescribeAssociationExecutionTargets`, `ssm:ListDocuments`,
-and `ssm:DescribePatchBaselines`.
+`ssm:DescribePatchBaselines`, `ssm:DescribeInstancePatchStates`, `ssm:DescribeInstancePatches`,
+`ssm:DescribeSessions`, `ssm:DescribeOpsItems`, and `ssm:ListOpsItemEvents`.
Enter an access key ID and secret access key. Include a session token for temporary credentials.
All tables use full refresh. Create a separate source for each region.""",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py
index 563cd7848fdf..3df5d33018b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_systems_manager/tests/test_aws_systems_manager.py
@@ -171,6 +171,14 @@ def test_rejects_unsupported_model_version(config: AwsSystemsManagerSourceConfig
"baseline_id",
100,
),
+ (
+ "ops_item_events",
+ "ListOpsItemEvents",
+ "Summaries",
+ {"EventId": "event-example", "OpsItemId": "oi-example"},
+ "event_id",
+ 50,
+ ),
],
)
@pytest.mark.parametrize("terminal_token", [None, ""])
@@ -440,19 +448,46 @@ def test_normalizes_nested_counts_timestamps_and_composite_keys(
assert rows[0]["execution_summary_execution_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
-def test_preserves_inventory_content(
+ "schema,result_key,item_id,key,column,data",
+ [
+ (
+ "inventory",
+ "Entities",
+ {"Id": "i-example"},
+ "Data",
+ "data",
+ {
+ "AWS:InstanceInformation": {
+ "CaptureTime": "2025-01-01T00:00:00Z",
+ "Content": [{"InstanceId": "i-example", "InstanceStatus": "Stopped"}],
+ }
+ },
+ ),
+ (
+ "ops_items",
+ "OpsItemSummaries",
+ {"OpsItemId": "oi-example"},
+ "OperationalData",
+ "operational_data",
+ {"/aws/resources": {"Value": '[{"arn": "arn:aws:ec2:example"}]', "Type": "SearchableString"}},
+ ),
+ ],
+)
+def test_preserves_dynamic_content_as_json(
config: AwsSystemsManagerSourceConfig,
+ schema: str,
+ result_key: str,
+ item_id: dict[str, Any],
+ key: str,
+ column: str,
+ data: dict[str, Any],
) -> None:
- data = {
- "AWS:InstanceInformation": {
- "CaptureTime": "2025-01-01T00:00:00Z",
- "Content": [{"InstanceId": "i-example", "InstanceStatus": "Stopped"}],
- }
- }
- result = driver(config).run("inventory", [ScriptedResponse(json={"Entities": [{"Id": "i-example", "Data": data}]})])
+ result = driver(config).run(schema, [ScriptedResponse(json={result_key: [{**item_id, key: data}]})])
assert result.raised is None
- row = result.rows[0]
- assert json.loads(row["data"]) == data
+ assert len(result.rows) == 1
+ assert json.loads(result.rows[0][column]) == data
+ assert not any(name.startswith(f"{column}_") for name in result.rows[0])
@pytest.mark.parametrize("incremental", [False, True])
@@ -634,6 +669,73 @@ def _instance(instance_id: str, status: str) -> dict[str, Any]:
}
],
),
+ (
+ "instance_patch_states",
+ [
+ ScriptedResponse(
+ json={
+ "InstanceInformationList": [{"InstanceId": "i-a"}, {"InstanceId": "mi-b"}],
+ "NextToken": "nodes-2",
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "InstancePatchStates": [
+ {"InstanceId": "i-a", "MissingCount": 3, "OperationEndTime": 1735689600},
+ {"InstanceId": "mi-b", "MissingCount": 0, "OperationEndTime": 1735689600},
+ ]
+ }
+ ),
+ ScriptedResponse(json={"InstanceInformationList": [{"InstanceId": "i-c"}]}),
+ ScriptedResponse(json={"InstancePatchStates": [{"InstanceId": "i-c", "MissingCount": 1}]}),
+ ],
+ [
+ ("DescribeInstanceInformation", {"MaxResults": 50}),
+ ("DescribeInstancePatchStates", {"MaxResults": 50, "InstanceIds": ["i-a", "mi-b"]}),
+ ("DescribeInstanceInformation", {"MaxResults": 50, "NextToken": "nodes-2"}),
+ ("DescribeInstancePatchStates", {"MaxResults": 50, "InstanceIds": ["i-c"]}),
+ ],
+ [
+ {
+ "instance_id": "i-a",
+ "missing_count": 3,
+ "operation_end_time": dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ },
+ {"instance_id": "mi-b", "missing_count": 0},
+ {"instance_id": "i-c", "missing_count": 1},
+ ],
+ ),
+ (
+ "instance_patches",
+ [
+ ScriptedResponse(json={"InstanceInformationList": [{"InstanceId": "i-a"}, {"InstanceId": "i-gone"}]}),
+ ScriptedResponse(
+ json={
+ "Patches": [
+ {"Title": "KB1 update", "KBId": "KB1", "State": "Missing", "InstalledTime": 0},
+ {"Title": "KB2 update", "KBId": "KB2", "State": "Installed", "InstalledTime": 1735689600},
+ ]
+ }
+ ),
+ _error("InvalidInstanceId"),
+ ],
+ [
+ ("DescribeInstanceInformation", {"MaxResults": 50}),
+ *(
+ ("DescribeInstancePatches", {"MaxResults": 100, "InstanceId": instance_id})
+ for instance_id in ["i-a", "i-gone"]
+ ),
+ ],
+ [
+ {"instance_id": "i-a", "kb_id": "KB1", "state": "Missing"},
+ {
+ "instance_id": "i-a",
+ "kb_id": "KB2",
+ "state": "Installed",
+ "installed_time": dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ },
+ ],
+ ),
],
)
def test_fan_out_requests_each_parent_row_and_skips_vanished_parents(
@@ -698,6 +800,37 @@ def test_fan_out_resumes_inside_nested_parent_without_rereading_done_children(
assert result.final_state == SystemsManagerResumeConfig(completed=True)
[email protected]("resumed", [False, True])
+def test_sessions_read_ended_then_active_sessions(config: AwsSystemsManagerSourceConfig, resumed: bool) -> None:
+ active = _key({"MaxResults": 200, "State": "Active"})
+ history = [
+ ScriptedResponse(json={"Sessions": [{"SessionId": "s-ended", "EndDate": 1735689600}], "NextToken": "h-2"}),
+ ScriptedResponse(json={"Sessions": []}),
+ ]
+ result = driver(config).run(
+ "sessions",
+ [
+ *([] if resumed else history),
+ ScriptedResponse(json={"Sessions": [{"SessionId": "s-open", "Status": "Connected"}]}),
+ ],
+ resume_state=SystemsManagerResumeConfig(parents=((None, active),), next_token="a-2") if resumed else None,
+ )
+ assert result.raised is None
+ expected_requests = [
+ *(
+ []
+ if resumed
+ else [{"MaxResults": 200, "State": "History"}, {"MaxResults": 200, "State": "History", "NextToken": "h-2"}]
+ ),
+ {"MaxResults": 200, "State": "Active", **({"NextToken": "a-2"} if resumed else {})},
+ ]
+ assert [request.json() for request in result.requests] == expected_requests
+ assert [row["session_id"] for row in result.rows] == ([] if resumed else ["s-ended"]) + ["s-open"]
+ if not resumed:
+ assert result.rows[0]["end_date"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+ assert result.final_state == SystemsManagerResumeConfig(completed=True)
+
+
_PLACEHOLDER_UUID = "00000000-0000-0000-0000-000000000000"