Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,15 @@ <Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Sco
* @param id the identifier of the source (parent) dataset
* @param select whether to derive from the unsolved input or the solved output of the parent
* @param runName a human-readable name for the new run
* @param tags the set of tags to attach to the new dataset
* @param modelInputPatchRequest the patch request containing the JSON patch operations and an optional
* {@link Configuration} override
* @return the {@link Metadata} of the newly created dataset
* @throws ai.timefold.solver.service.definition.internal.error.ItemNotFoundException
* if no dataset exists for the given id
*/
<Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Score_> patchDataset(String id,
DatasetSelector select, String runName,
DatasetSelector select, String runName, Set<String> tags,
ModelInputPatchRequest<ModelConfigurationOverrides_> modelInputPatchRequest);

/**
Expand All @@ -113,14 +114,15 @@ <Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Sco
* @param id the identifier of the source (parent) dataset
* @param select whether to derive from the unsolved input or the solved output of the parent
* @param runName a human-readable name for the new run
* @param tags the set of tags to attach to the new dataset
* @param modelInputPatchRequest the patch request containing the JSON patch operations and an optional
* {@link Configuration} override
* @return the {@link Metadata} of the newly created dataset
* @throws ai.timefold.solver.service.definition.internal.error.ItemNotFoundException
* if no dataset exists for the given id
*/
<Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Score_> patchAndSolveDataset(String id,
DatasetSelector select, String runName,
DatasetSelector select, String runName, Set<String> tags,
ModelInputPatchRequest<ModelConfigurationOverrides_> modelInputPatchRequest);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,15 +232,8 @@ public Metadata<Score_> fromInput(
@Validated(nullable = true,
operationId = OperationId.FROM_INPUT) Configuration<ModelConfigurationOverrides_> configuration) {

Set<String> tags = null;
String runName = null;

if (configuration != null && configuration.run() != null) {
RunConfiguration runConfiguration = configuration.run();
runName = runConfiguration.name();
tags = runConfiguration.tags();
}
runName = name == null ? runName : name;
String runName = runName(name, configuration);
Set<String> tags = runTags(configuration);

return switch (operation) {
case OperationOnPost.NONE -> solverWorkerFacade.createDataset(id, select, runName, tags, configuration);
Expand Down Expand Up @@ -279,10 +272,15 @@ public Metadata<Score_> fromPatch(
description = "Operation to execute on the POST request.") @DefaultValue(OperationOnPost.DEFAULT_OPERATION) @QueryParam("operation") OperationOnPost operation,
@Validated(nullable = true,
operationId = OperationId.FROM_PATCH) ModelInputPatchRequest<ModelConfigurationOverrides_> patchRequest) {
Configuration<ModelConfigurationOverrides_> configuration = patchRequest == null ? null : patchRequest.config();
String runName = runName(name, configuration);
Set<String> tags = runTags(configuration);

try {
return switch (operation) {
case OperationOnPost.NONE -> solverWorkerFacade.patchDataset(id, select, name, patchRequest);
case OperationOnPost.SOLVE -> solverWorkerFacade.patchAndSolveDataset(id, select, name, patchRequest);
case OperationOnPost.NONE -> solverWorkerFacade.patchDataset(id, select, runName, tags, patchRequest);
case OperationOnPost.SOLVE ->
solverWorkerFacade.patchAndSolveDataset(id, select, runName, tags, patchRequest);
};
} catch (IllegalArgumentException e) {
throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST)
Expand Down Expand Up @@ -582,4 +580,19 @@ public Response getValidationIssueTypeByCode(
}
return Response.status(Response.Status.NOT_FOUND).build();
}

/**
* Returns the name of a dataset that is created from another dataset: the name query parameter wins over the name
* of the run configuration.
*/
private static String runName(String name, Configuration<?> configuration) {
if (name != null || configuration == null || configuration.run() == null) {
return name;
}
return configuration.run().name();
}

private static Set<String> runTags(Configuration<?> configuration) {
return configuration == null || configuration.run() == null ? null : configuration.run().tags();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package ai.timefold.solver.service.rest.impl;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import ai.timefold.solver.service.definition.api.dto.dataset.Configuration;
import ai.timefold.solver.service.definition.api.dto.dataset.ModelConfigOverrides;
import ai.timefold.solver.service.definition.api.dto.dataset.ModelInput;
import ai.timefold.solver.service.definition.api.dto.dataset.ModelOutput;
import ai.timefold.solver.service.definition.api.dto.dataset.RunConfiguration;
import ai.timefold.solver.service.definition.api.dto.patch.ModelInputPatchRequest;
import ai.timefold.solver.service.definition.api.dto.scoreanalysis.ModelConstraintJustification;
import ai.timefold.solver.service.definition.api.dto.validation.issue.Issue;
import ai.timefold.solver.service.definition.api.metrics.ModelInputMetrics;
import ai.timefold.solver.service.definition.api.metrics.ModelOutputMetrics;
import ai.timefold.solver.service.definition.api.rest.DatasetSelector;
import ai.timefold.solver.service.definition.api.rest.OperationOnPost;
import ai.timefold.solver.service.definition.impl.solver.SolverWorkerFacade;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class AbstractModelAPIResourceTest {

private static final Configuration<ModelConfigOverrides> CONFIGURATION = Configuration.<ModelConfigOverrides> empty()
.withRun(new RunConfiguration("config-name", null, null, Set.of("config-tag")));

private final AtomicReference<FacadeCall> lastFacadeCall = new AtomicReference<>();
private final AbstractModelAPIResource<ModelInput, ModelOutput, ModelConfigOverrides, Object, ModelInputMetrics, ModelOutputMetrics, ModelConstraintJustification, Issue> resource =
new AbstractModelAPIResource<>(null, recordingFacade(), null) {
};

@ParameterizedTest
@CsvSource(nullValues = "null", value = {
"null, NONE, patchDataset, config-name",
"query-name, NONE, patchDataset, query-name",
"null, SOLVE, patchAndSolveDataset, config-name" })
void fromPatchTakesTheNameAndTheTagsOfTheRunConfiguration(String name, OperationOnPost operation, String expectedMethod,
String expectedRunName) {
var patchRequest = new ModelInputPatchRequest<>(CONFIGURATION, List.of());

resource.fromPatch("parent-id", name, DatasetSelector.UNSOLVED, operation, patchRequest);

assertThat(lastFacadeCall.get().method()).isEqualTo(expectedMethod);
assertThat(lastFacadeCall.get().arguments())
.containsExactly("parent-id", DatasetSelector.UNSOLVED, expectedRunName, Set.of("config-tag"), patchRequest);
}

@Test
void fromPatchWithoutConfigurationTakesTheNameQueryParameterOnly() {
var patchRequest = new ModelInputPatchRequest<ModelConfigOverrides>(null, List.of());

resource.fromPatch("parent-id", "query-name", DatasetSelector.UNSOLVED, OperationOnPost.NONE, patchRequest);

assertThat(lastFacadeCall.get().arguments())
.containsExactly("parent-id", DatasetSelector.UNSOLVED, "query-name", null, patchRequest);
}

@ParameterizedTest
@CsvSource(nullValues = "null", value = { "null, config-name", "query-name, query-name" })
void fromInputTakesTheNameAndTheTagsOfTheRunConfiguration(String name, String expectedRunName) {
resource.fromInput("parent-id", name, DatasetSelector.UNSOLVED, OperationOnPost.NONE, CONFIGURATION);

assertThat(lastFacadeCall.get().method()).isEqualTo("createDataset");
assertThat(lastFacadeCall.get().arguments())
.containsExactly("parent-id", DatasetSelector.UNSOLVED, expectedRunName, Set.of("config-tag"), CONFIGURATION);
}

private SolverWorkerFacade recordingFacade() {
return (SolverWorkerFacade) Proxy.newProxyInstance(SolverWorkerFacade.class.getClassLoader(),
new Class<?>[] { SolverWorkerFacade.class },
(proxy, method, arguments) -> {
lastFacadeCall.set(new FacadeCall(method.getName(), arguments));
return null;
});
}

private record FacadeCall(String method, Object[] arguments) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,43 @@ void uploadOnlySchedule() {
assertThat(response.outputMetrics().assignedShifts()).isZero();
}

static Stream<Arguments> fromPatchNameScenarios() {
return Stream.of(
Arguments.of(null, "from-patch-config-name"),
Arguments.of("from-patch-query-name", "from-patch-query-name"));
}

@ParameterizedTest
@MethodSource("fromPatchNameScenarios")
void fromPatchTakesTheNameAndTagsOfTheRunConfiguration(String queryName, String expectedName) {
Metadata<HardMediumSoftScore> metadata = post(createInputEmployeeSchedule(), OperationOnPost.NONE);

// The name query parameter wins over config.run.name, as in from-input.
Metadata<HardMediumSoftScore> patchedMetadata = given()
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.body("""
{"config": {"run": {"name": "from-patch-config-name", "tags": ["from-patch-tag"]}}, "patch": []}""")
.when()
.post("/schedules/" + metadata.getId() + "/from-patch?select=UNSOLVED&operation="
+ OperationOnPost.NONE.name() + (queryName == null ? "" : "&name=" + queryName))
.then()
.log().ifError()
.statusCode(202)
.extract()
.as(new TypeRef<>() {
});

assertThat(patchedMetadata.getName()).isEqualTo(expectedName);
assertThat(patchedMetadata.getTags()).containsExactly("from-patch-tag");

// Await both datasets so the asynchronous computation cannot leak into the next test.
await()
.atMost(TEST_AWAIT_TIMEOUT_DURATION)
.pollInterval(TEST_POLL_INTERVAL_MILLIS)
.until(() -> datasetComputedSink.received().size() >= 2);
}

@Test
@Disabled("Flaky test")
void solveEmployeeScheduleWithWatching() throws InterruptedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,18 +137,18 @@ public <Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metad

@Override
public <Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Score_> patchDataset(String id,
DatasetSelector select, String runName,
DatasetSelector select, String runName, Set<String> tags,
ModelInputPatchRequest<ModelConfigurationOverrides_> modelInputPatchRequest) {
var metadata = createPatchedDataset(id, select, runName, modelInputPatchRequest);
var metadata = createPatchedDataset(id, select, runName, tags, modelInputPatchRequest);
datasetValidateComputeCommandEmitter.send(new DatasetValidateComputeCommand(metadata.getId(), false));
return metadata;
}

@Override
public <Score_, ModelConfigurationOverrides_ extends ModelConfigOverrides> Metadata<Score_> patchAndSolveDataset(String id,
DatasetSelector select, String runName,
DatasetSelector select, String runName, Set<String> tags,
ModelInputPatchRequest<ModelConfigurationOverrides_> modelInputPatchRequest) {
var metadata = createPatchedDataset(id, select, runName, modelInputPatchRequest);
var metadata = createPatchedDataset(id, select, runName, tags, modelInputPatchRequest);
datasetValidateComputeCommandEmitter.send(new DatasetValidateComputeCommand(metadata.getId(), true));
return metadata;
}
Expand Down Expand Up @@ -272,7 +272,7 @@ private Metadata createDatasetInternal(String id, DatasetSelector select, String
return metadata;
}

private Metadata createPatchedDataset(String id, DatasetSelector select, String runName,
private Metadata createPatchedDataset(String id, DatasetSelector select, String runName, Set<String> tags,
ModelInputPatchRequest patchRequest) {
var input =
select == DatasetSelector.UNSOLVED ? getModelInput(id) : getSolvedModelInput(id);
Expand All @@ -295,6 +295,7 @@ private Metadata createPatchedDataset(String id, DatasetSelector select, String
ModelInput patchedModelInput = mapper.treeToValue(patchedInput, input.getClass());

Metadata metadata = new Metadata<>(runName);
metadata.setTags(tags);
// set parent id to the id this data set is created from
metadata.setParentId(id);
// set origin id based on the origin id of the parent data set
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ void createAndSolveDataset_fromExistingDataset_emitsValidateComputeWithSolveTrue
void patchDataset_missingParent_throwsItemNotFound() {
ModelInputPatchRequest<?> patch = new ModelInputPatchRequest<>(null, List.of());

assertThatThrownBy(() -> facade.patchDataset("missing", DatasetSelector.UNSOLVED, uniqueRunName(), patch))
assertThatThrownBy(() -> facade.patchDataset("missing", DatasetSelector.UNSOLVED, uniqueRunName(), Set.of(), patch))
.isInstanceOf(ItemNotFoundException.class);
assertThat(validateComputeEmitter.size()).isEqualTo(0);
}
Expand All @@ -205,12 +205,17 @@ void patchDataset_emitsValidateComputeWithoutSolve() {
var childRunName = uniqueRunName();

ModelInputPatchRequest<?> patch = new ModelInputPatchRequest<>(null, List.of());
Metadata<?> child = facade.patchDataset(parent.getId(), DatasetSelector.UNSOLVED, childRunName, patch);
Metadata<?> child = facade.patchDataset(parent.getId(), DatasetSelector.UNSOLVED, childRunName, Set.of("patch-tag"),
patch);

// emitter assertions
assertThat(validateComputeEmitter.size()).isEqualTo(1);
assertThat(validateComputeEmitter.getLastMessage().solve()).isFalse();

// metadata assertions
assertThat(child.getName()).isEqualTo(childRunName);
assertThat(child.getTags()).containsExactly("patch-tag");

// storage assertions — child dataset is stored independently with parent linkage
assertThat(child.getParentId()).isEqualTo(parent.getId());
assertThat(child.getOriginId()).isEqualTo(parent.getOriginId());
Expand All @@ -233,12 +238,15 @@ void patchAndSolveDataset_emitsValidateComputeWithSolveTrue() {

ModelInputPatchRequest<?> patch = new ModelInputPatchRequest<>(null, List.of());
Metadata<?> child = facade.patchAndSolveDataset(
parent.getId(), DatasetSelector.UNSOLVED, uniqueRunName(), patch);
parent.getId(), DatasetSelector.UNSOLVED, uniqueRunName(), Set.of("patch-tag"), patch);

// emitter assertions
assertThat(validateComputeEmitter.size()).isEqualTo(1);
assertThat(validateComputeEmitter.getLastMessage().solve()).isTrue();

// metadata assertions
assertThat(child.getTags()).containsExactly("patch-tag");

// storage assertions
assertThat(child.getParentId()).isEqualTo(parent.getId());
assertThat(child.getOriginId()).isEqualTo(parent.getOriginId());
Expand Down
Loading