From 0e782b62f298b12164ad2ba0a91caf0f75893e49 Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:23:37 +0100 Subject: [PATCH] fix(sagemaker): filter ListModels by CreationTimeAfter and CreationTimeBefore (#8766) ListModels ignored CreationTimeAfter and CreationTimeBefore and returned every model. Both now filter before paging, beside NameContains: CreationTimeAfter keeps the models created at or after its time and CreationTimeBefore those created before it, as the ListModels reference describes, and a bound that is not a number is a SerializationException. The page token records both bounds, so a token reused with a changed bound is refused with a ValidationException, as ListTrainingJobs does for its filters. Closes #7627 --- docs/services/sagemaker.md | 2 +- .../services/sagemaker/SageMakerService.java | 24 ++++++- ...ListModelsCreationTimeIntegrationTest.java | 72 +++++++++++++++++++ .../SageMakerListSortServiceTest.java | 69 ++++++++++++++++-- 4 files changed, 158 insertions(+), 9 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/sagemaker/SageMakerListModelsCreationTimeIntegrationTest.java diff --git a/docs/services/sagemaker.md b/docs/services/sagemaker.md index f276e80fe5..da53a1324d 100644 --- a/docs/services/sagemaker.md +++ b/docs/services/sagemaker.md @@ -21,7 +21,7 @@ Floci emulates SageMaker control-plane APIs and runs real Docker containers for | `CreateModel` | Registers a model from `PrimaryContainer` or `Containers`; rejects an empty `Containers` array rather than dereferencing it. | | `DescribeModel` | Returns a model by name, scoped to the calling region. | | `DeleteModel` | Deletes a model by name, scoped to the calling region. | -| `ListModels` | Lists models for the calling region; supports `NameContains`, `MaxResults` (1-100), and `NextToken` pagination. | +| `ListModels` | Lists models for the calling region; supports `NameContains`, `CreationTimeAfter`, `CreationTimeBefore`, `MaxResults` (1-100), and `NextToken` pagination. | | `CreateEndpointConfig` | Creates an endpoint configuration; every `ProductionVariants[].ModelName` must already exist. | | `DescribeEndpointConfig` | Returns an endpoint configuration by name, scoped to the calling region. | | `DeleteEndpointConfig` | Deletes an endpoint configuration by name, scoped to the calling region. | diff --git a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java index 3d910ad470..ab2f9033f0 100644 --- a/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java +++ b/src/main/java/io/floci/aws/services/sagemaker/SageMakerService.java @@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.AwsJsonTimestamp; import io.floci.aws.core.common.Base64Url; import io.floci.aws.core.common.EpochSeconds; import io.floci.aws.core.common.RegionResolver; @@ -23,6 +24,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.time.Clock; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -156,9 +158,19 @@ public class SageMakerService { if (nameContains != null && !nameContains.isBlank()) { models = models.stream().filter(m -> m.modelName.contains(nameContains)).toList(); } + Instant createdAfter = AwsJsonTimestamp.epochSeconds(request, "CreationTimeAfter", "SerializationException"); + if (createdAfter != null) { + models = models.stream().filter(m -> m.creationTime >= createdAfter.toEpochMilli()).toList(); + } + Instant createdBefore = AwsJsonTimestamp.epochSeconds(request, "CreationTimeBefore", "SerializationException"); + if (createdBefore != null) { + models = models.stream().filter(m -> m.creationTime < createdBefore.toEpochMilli()).toList(); + } + String creationTimes = createdAfter == null && createdBefore == null ? "" + : createdAfter + "/" + createdBefore; return paginate(models, request, sortBy, sortOrder, new CursorScope("ListModels", region, - nameContains == null || nameContains.isBlank() ? "" : nameContains, ""), + nameContains == null || nameContains.isBlank() ? "" : nameContains, "", creationTimes), m -> modelCursor(m, sortBy, sortOrder), m -> modelAnchor(m, sortBy), comparator, (m, n) -> { n.put("ModelName", m.modelName); @@ -683,6 +695,7 @@ public class SageMakerService { private record SortOptions(String sortBy, String sortOrder) { } + private static Comparator modelComparator(String sortBy, String sortOrder) { Comparator comparator = "Name".equals(sortBy) ? Comparator.comparing(m -> m.modelName) @@ -833,6 +846,7 @@ public class SageMakerService { token.put("sortOrder", cursor.sortOrder()); token.put("nameContains", scope.nameContains()); token.put("statusEquals", scope.statusEquals()); + token.put("creationTimes", scope.creationTimes()); token.put("value", cursor.value()); token.put("name", cursor.name()); return Base64Url.encode(token.toString()); @@ -851,6 +865,7 @@ public class SageMakerService { || !sortOrder.equals(cursor.path("sortOrder").asText(null)) || !scope.nameContains().equals(cursor.path("nameContains").asText(null)) || !scope.statusEquals().equals(cursor.path("statusEquals").asText(null)) + || !scope.creationTimes().equals(cursor.path("creationTimes").asText("")) || !cursor.path("value").isTextual() || !cursor.path("name").isTextual() || cursor.path("name").asText().isBlank()) { @@ -865,7 +880,12 @@ public class SageMakerService { private record SortCursor(String sortBy, String sortOrder, String value, String name) { } - private record CursorScope(String operation, String region, String nameContains, String statusEquals) { + private record CursorScope(String operation, String region, String nameContains, String statusEquals, + String creationTimes) { + + CursorScope(String operation, String region, String nameContains, String statusEquals) { + this(operation, region, nameContains, statusEquals, ""); + } } private ObjectNode page(List remaining, int max, BiConsumer render, diff --git a/src/test/java/io/floci/aws/services/sagemaker/SageMakerListModelsCreationTimeIntegrationTest.java b/src/test/java/io/floci/aws/services/sagemaker/SageMakerListModelsCreationTimeIntegrationTest.java new file mode 100644 index 0000000000..c4774efb14 --- /dev/null +++ b/src/test/java/io/floci/aws/services/sagemaker/SageMakerListModelsCreationTimeIntegrationTest.java @@ -0,0 +1,72 @@ +package io.floci.aws.services.sagemaker; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sagemaker.SageMakerClient; +import software.amazon.awssdk.services.sagemaker.model.ListModelsRequest; +import software.amazon.awssdk.services.sagemaker.model.ListModelsResponse; +import software.amazon.awssdk.services.sagemaker.model.ModelSummary; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** {@code ListModels} returns only the models created inside its {@code CreationTimeAfter}/{@code Before} window. */ +@QuarkusTest +class SageMakerListModelsCreationTimeIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + + @Test + void creationTimeFiltersKeepOnlyTheModelsCreatedInTheirWindow() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + List created = List.of("window-a-" + suffix, "window-b-" + suffix); + try (SageMakerClient sagemaker = AwsTestClients.create(SageMakerClient.builder(), ACCOUNT, Region.US_EAST_1)) { + try { + created.forEach(name -> createModel(sagemaker, name)); + Instant createdAt = sagemaker.describeModel(r -> r.modelName(created.getFirst())).creationTime(); + Instant before = createdAt.minus(Duration.ofHours(1)); + Instant after = createdAt.plus(Duration.ofHours(1)); + + assertEquals(List.of(), names(sagemaker, suffix, r -> r.creationTimeBefore(Instant.EPOCH))); + assertEquals(List.of(), names(sagemaker, suffix, r -> r.creationTimeAfter(after))); + assertEquals(created, names(sagemaker, suffix, r -> r.creationTimeAfter(before))); + assertEquals(created, names(sagemaker, suffix, r -> r.creationTimeBefore(after))); + assertEquals(created, names(sagemaker, suffix, + r -> r.creationTimeAfter(before).creationTimeBefore(after))); + } finally { + created.forEach(name -> sagemaker.deleteModel(r -> r.modelName(name))); + } + } + } + + /** The names of the models whose name holds {@code suffix}, by name, one page at a time. */ + private static List names(SageMakerClient sagemaker, String suffix, + Consumer filter) { + List names = new ArrayList<>(); + String token = null; + do { + String next = token; + ListModelsResponse page = sagemaker.listModels(r -> { + filter.accept(r.nameContains(suffix).sortBy("Name").sortOrder("Ascending").maxResults(1)); + r.nextToken(next); + }); + page.models().stream().map(ModelSummary::modelName).forEach(names::add); + token = page.nextToken(); + } while (token != null); + return names; + } + + private static void createModel(SageMakerClient sagemaker, String name) { + sagemaker.createModel(r -> r.modelName(name) + .executionRoleArn("arn:aws:iam::" + ACCOUNT + ":role/sagemaker") + .primaryContainer(c -> c.image("123456789012.dkr.ecr.us-east-1.amazonaws.com/model:latest"))); + } +} diff --git a/src/test/java/io/floci/aws/services/sagemaker/SageMakerListSortServiceTest.java b/src/test/java/io/floci/aws/services/sagemaker/SageMakerListSortServiceTest.java index 7bba573bd4..f7c88b848f 100644 --- a/src/test/java/io/floci/aws/services/sagemaker/SageMakerListSortServiceTest.java +++ b/src/test/java/io/floci/aws/services/sagemaker/SageMakerListSortServiceTest.java @@ -131,7 +131,7 @@ class SageMakerListSortServiceTest { second.trainingJobStatus = "InProgress"; jobs.put(REGION + "::b-job", first); jobs.put(REGION + "::a-job", second); - SageMakerService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), jobs, + SageMakerService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), jobs, mapperMutatingBeforeRender(() -> first.trainingJobStatus = "Completed")); ObjectNode request = mapper.createObjectNode() .put("SortBy", "Status").put("SortOrder", "Descending").put("MaxResults", 1); @@ -153,8 +153,8 @@ class SageMakerListSortServiceTest { EndpointResource second = endpoint("a-endpoint"); endpoints.put(REGION + "::b-endpoint", first); endpoints.put(REGION + "::a-endpoint", second); - SageMakerService service = service(new InMemoryStorage<>(), endpoints, new InMemoryStorage<>(), - mapperMutatingBeforeRender(() -> first.endpointStatus = "Creating")); + SageMakerService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), endpoints, + new InMemoryStorage<>(), mapperMutatingBeforeRender(() -> first.endpointStatus = "Creating")); ObjectNode request = mapper.createObjectNode() .put("SortBy", "Status").put("SortOrder", "Descending").put("MaxResults", 1); @@ -311,6 +311,62 @@ class SageMakerListSortServiceTest { assertEquals("ValidationException", changedStatus.getErrorCode()); } + @Test + void listModelsCursorRejectsChangedCreationTimeFilters() throws Exception { + SageMakerService service = modelService(model("older", 1000), model("newer", 3000)); + JsonNode first = service.listModels(mapper.createObjectNode() + .put("CreationTimeAfter", 0.5).put("MaxResults", 1), REGION); + String cursor = first.path("NextToken").asText(); + + JsonNode sameFilter = service.listModels(mapper.createObjectNode() + .put("CreationTimeAfter", 0.5).put("NextToken", cursor), REGION); + assertEquals(List.of("older"), names(sameFilter, "Models", "ModelName")); + AwsException changedAfter = assertThrows(AwsException.class, () -> service.listModels( + mapper.createObjectNode().put("CreationTimeAfter", 0.6).put("NextToken", cursor), REGION)); + assertEquals("ValidationException", changedAfter.getErrorCode()); + AwsException addedBefore = assertThrows(AwsException.class, () -> service.listModels( + mapper.createObjectNode().put("CreationTimeAfter", 0.5).put("CreationTimeBefore", 9.0) + .put("NextToken", cursor), REGION)); + assertEquals("ValidationException", addedBefore.getErrorCode()); + } + + @Test + void listModelsCreationTimeAfterIncludesAModelCreatedAtItsTimeAndBeforeExcludesIt() throws Exception { + SageMakerService service = modelService(model("exact", 1000)); + + JsonNode after = service.listModels(mapper.createObjectNode().put("CreationTimeAfter", 1.0), REGION); + JsonNode before = service.listModels(mapper.createObjectNode().put("CreationTimeBefore", 1.0), REGION); + + assertEquals(List.of("exact"), names(after, "Models", "ModelName")); + assertEquals(List.of(), names(before, "Models", "ModelName")); + } + + @Test + void listModelsRejectsACreationTimeThatIsNotATimestamp() throws Exception { + SageMakerService service = modelService(model("any", 1000)); + + AwsException e = assertThrows(AwsException.class, () -> service.listModels( + mapper.createObjectNode().put("CreationTimeBefore", "not-a-timestamp"), REGION)); + + assertEquals("SerializationException", e.getErrorCode()); + } + + private SageMakerService modelService(ModelResource... models) { + InMemoryStorage store = new InMemoryStorage<>(); + for (ModelResource m : models) { + store.put(REGION + "::" + m.modelName, m); + } + return service(store, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), mapper); + } + + private static ModelResource model(String name, long creationTime) { + ModelResource m = new ModelResource(); + m.modelName = name; + m.modelArn = "arn:aws:sagemaker:us-east-1:000000000000:model/" + name; + m.creationTime = creationTime; + return m; + } + @Test void listRejectsUnmodeledSortValues() throws Exception { SageMakerService service = service(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); @@ -355,14 +411,15 @@ class SageMakerListSortServiceTest { private SageMakerService service(InMemoryStorage configs, InMemoryStorage endpoints, InMemoryStorage jobs) { - return service(configs, endpoints, jobs, mapper); + return service(new InMemoryStorage<>(), configs, endpoints, jobs, mapper); } - private SageMakerService service(InMemoryStorage configs, + private SageMakerService service(InMemoryStorage models, + InMemoryStorage configs, InMemoryStorage endpoints, InMemoryStorage jobs, ObjectMapper serviceMapper) { - return new SageMakerService(new InMemoryStorage(), configs, endpoints, jobs, + return new SageMakerService(models, configs, endpoints, jobs, new RegionResolver(REGION, "000000000000"), serviceMapper, mock(SageMakerEndpointManager.class), mock(SageMakerTrainingRunner.class)); }