Skip to main content

Numerical Preprocessing

Original integration-test class: PreprocessingNumerical in 4.3.1.2.ML.Preprocessing.Numerical.cs. This is a direct SDK operation, not a PipelineClient workflow.

150 recorded job or prediction directories matched by module and scenario path. 150 have completed/success status and a saved result. These are API execution records, not confirmed xUnit pass counts. Partition jobs are counted separately.

Prerequisites​

Use the original SDK test project, its xUnit dependencies, helper classes and any upstream cache entries referenced in the source. See configuration.

Required environment variable names referenced in the source: PARALLELMODEL_MODEL_ID, PARALLELMODEL_COMPUTE_SIZE, PARALLELMODEL_ENCRYPTION_KEY_1, PARALLELMODEL_REGION, PARALLELMODEL_CLIENT_ID, PARALLELMODEL_CLIENT_SECRET.

SDK calls used​

ClientMethods in the source
PreprocessingClientDownloadBytesAsync, ExtractAsync, LogAsync, ResultAsync, SendAsync, StatusAsync

Execution workflow​

  1. Initialise client and output paths.
  2. Read the current imputed.csv artifacts and their request metadata.
  3. Send one strongly typed request and save the original response.
  4. Poll status and save each response before interpreting it.
  5. Retrieve logs; stop after the first successful response.
  6. Retrieve and save the original result.
  7. Extract and download every declared artifact.
  8. Publish both partitions atomically only after both complete.

Recorded operation examples​

OperationRecorded jobsResult recorded
FunctionTransformer1212
KBinsDiscretizer3030
QuantileTransformer3030
StandardScaler3030
label_binarize1818
normalize3030

Run the original integration test​

This filter selects the class and its parameterized scenarios; it does not select only a single recorded job.

dotnet test --filter "FullyQualifiedName~ParallelModel.Sdk.UnitTests.PreprocessingNumerical.Run"

Full C# source​

The supplied test logic is preserved. The method signature is:

Run(string datasetName, string selectionName, string impute, string name)
using ParallelModel.Sdk.Authentication;
using ParallelModel.Sdk.Exceptions;
using ParallelModel.Sdk.ML.Preprocessing.Models;
using ParallelModel.Sdk.ML.Preprocessing.Models.Requests;
using ParallelModel.Sdk.Shared.Blob;
using ParallelModel.Sdk.UnitTests.Attributes;
using ParallelModel.Sdk.UnitTests.Cache;
using ParallelModel.Sdk.UnitTests.Helpers;
using System.Text.Json;

namespace ParallelModel.Sdk.UnitTests;

[Collection("Preprocessing")]
public sealed class PreprocessingNumerical
{
private static readonly SharedSendThrottle sendThrottle = new(TimeSpan.FromSeconds(12));
private static readonly TimeSpan ApiTimeout = TimeSpan.FromSeconds(300);
private static readonly string[] Algorithms = { "FunctionTransformer", "KBinsDiscretizer", "label_binarize",
"normalize", "OneHotEncoder", "QuantileTransformer", "StandardScaler" };

public static TheoryData<string, string, string, string> PreprocessingRequests =>
ImputeAttribute.GetRequests(typeof(PreprocessingNumerical), nameof(Run), PreprocessingAlgorithmsFor);

private static string[] PreprocessingAlgorithmsFor(string datasetName) =>
MLDatasetHelper.ResolveDatasetProfile(datasetName).IsClassification
? Algorithms
: Algorithms.Where(algorithm => algorithm != "label_binarize").ToArray();

[Theory]
[Trait("Category", "Integration")]
[MemberData(nameof(PreprocessingRequests))]
[Impute("LoadDiabetes", "TrainTestSplit", "SimpleImputer")]
[Impute("LoadDiabetes", "TrainTestSplit", "KNNImputer")]
[Impute("LoadDiabetes", "TrainTestSplit", "IterativeImputer")]
[Impute("LoadBreastCancer", "TrainTestSplit", "SimpleImputer")]
[Impute("LoadBreastCancer", "TrainTestSplit", "KNNImputer")]
[Impute("LoadBreastCancer", "TrainTestSplit", "IterativeImputer")]
[Impute("LoadWine", "TrainTestSplit", "SimpleImputer")]
[Impute("LoadWine", "TrainTestSplit", "KNNImputer")]
[Impute("LoadWine", "TrainTestSplit", "IterativeImputer")]
[Impute("MakeClassification", "TrainTestSplit", "SimpleImputer")]
[Impute("MakeClassification", "TrainTestSplit", "KNNImputer")]
[Impute("MakeClassification", "TrainTestSplit", "IterativeImputer")]
[Impute("MakeRegression", "TrainTestSplit", "SimpleImputer")]
[Impute("MakeRegression", "TrainTestSplit", "KNNImputer")]
[Impute("MakeRegression", "TrainTestSplit", "IterativeImputer")]
public async Task Run(string datasetName, string selectionName, string impute, string name)
{
// 1. Initialise client and output paths.
SharedEnvironmentHelper.LoadEnvIfAvailable();
CancellationToken cancellationToken = TestContext.Current.CancellationToken;
Guid modelId = SharedEnvironmentHelper.RequiredGuid("PARALLELMODEL_MODEL_ID");
string computeSize = SharedEnvironmentHelper.Required("PARALLELMODEL_COMPUTE_SIZE");
string encryptionKey = SharedEnvironmentHelper.Required("PARALLELMODEL_ENCRYPTION_KEY_1");
TimeSpan pollingInterval = TimeSpan.FromSeconds(30);
ParallelModelClient client = new(new DefaultParallelModelAuthenticationOptions
{
Region = SharedEnvironmentHelper.Required("PARALLELMODEL_REGION"),
ClientId = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_ID"),
ClientSecret = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_SECRET"),
Timeout = TimeSpan.FromSeconds(90),
AutoRefreshToken = true,
RefreshBeforeExpiry = TimeSpan.FromMinutes(2),
RetryOnUnauthorized = true,
MaxRetries = 3
});
string cacheDirectory = SharedEnvironmentHelper.CacheDirectory;
string runId = Guid.NewGuid().ToString("N");
string runDirectory = Path.Combine(SharedEnvironmentHelper.OutputDirectory,
"preprocessing.numerical", datasetName, selectionName, impute, name, runId);

// 2. Read the current imputed.csv artifacts and their request metadata.
IReadOnlyList<MLPreprocessingHelper.ImputedArtifact> sourceArtifacts =
await MLPreprocessingHelper.LoadImputedPairAsync(datasetName, selectionName, impute,
cacheDirectory, ImputeCacheEntry.NumericalFileName, cancellationToken);
ParallelModelBlobClient blobClient = new(client);
MLPreprocessingHelper.ImputedArtifact trainArtifact = sourceArtifacts[0];
MLPreprocessingHelper.ImputedArtifact testArtifact = sourceArtifacts[1];
byte[] trainBytes = await blobClient.DownloadBytesAsync(modelId, trainArtifact.BlobId,
encryptionKey, ApiTimeout).WaitAsync(cancellationToken);
byte[] testBytes = await blobClient.DownloadBytesAsync(modelId, testArtifact.BlobId,
encryptionKey, ApiTimeout).WaitAsync(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
bool classification = name == "label_binarize";
MLPreprocessingHelper.PreprocessingInput trainInput = MLPreprocessingHelper.ReadInput(trainArtifact,
trainBytes, classification, false);
MLPreprocessingHelper.PreprocessingInput testInput = MLPreprocessingHelper.ReadInput(testArtifact,
testBytes, classification, false);
(trainInput, testInput) = MLPreprocessingHelper.AlignRequestMetadata(trainInput, testInput);
if (name != "label_binarize" && trainInput.NumericColumns.Count == 0)
throw new InvalidOperationException("No shared numeric feature columns for the preprocessing request.");
string? skipReason = name switch
{
"FunctionTransformer" when trainInput.NonNegativeColumns.Count == 0 =>
"log1p requires nonnegative numeric features in both partitions.",
"KBinsDiscretizer" when trainInput.VaryingColumns.Count == 0 =>
"Requires at least one varying training feature present in both partitions.",
"label_binarize" when trainInput.TargetClasses.Count < 2 =>
"Requires at least two training target classes.",
"OneHotEncoder" when trainInput.DiscreteColumns.Count == 0 =>
"Requires a low-cardinality integer feature in both partitions.",
"QuantileTransformer" when Math.Min(trainInput.RowCount, testInput.RowCount) < 2 =>
"Requires at least two rows in each partition.",
_ => null
};
if (skipReason is not null)
Assert.Skip(skipReason);

List<PreprocessingCacheEntry> cacheEntries = new();
foreach ((MLPreprocessingHelper.ImputedArtifact artifact, MLPreprocessingHelper.PreprocessingInput input) in
new[] { (trainArtifact, trainInput), (testArtifact, testInput) })
{
string outputDirectory = Path.Combine(runDirectory, artifact.Partition);
Directory.CreateDirectory(Path.Combine(outputDirectory, "artifacts"));
int responseFileNumber = 0;

// 3. Send one strongly typed request and save the original response.
await sendThrottle.WaitForSendSlotAsync(cancellationToken);
string requestFileName = NextFileName("request");
ParallelModelPreprocessingSendResponseModel sendResponse = await RequestAsync("send", () =>
SendPreprocessingAsync(name, client, modelId, input, computeSize, encryptionKey,
outputDirectory, requestFileName, cancellationToken));
Guid jobId = sendResponse.JobId;
if (jobId == Guid.Empty)
throw new InvalidOperationException("Preprocessing send did not return a job ID.");

// 4. Poll status and save each response before interpreting it.
DateTimeOffset statusDeadline = DateTimeOffset.UtcNow.AddMinutes(10);
int pollNumber = 0;
while (true)
{
if (DateTimeOffset.UtcNow >= statusDeadline)
throw new TimeoutException($"Preprocessing job {jobId} did not finish before the status deadline.");
ParallelModelPreprocessingStatusResponseModel status = await RequestAsync(
$"status-{++pollNumber:000}", () => client.PreprocessingClient.StatusAsync(
modelId, jobId, computeSize, ApiTimeout, cancellationToken),
maximumAttempts: int.MaxValue, retryDeadline: statusDeadline);
if (status is not ParallelModelPreprocessingStatusResponseModel.Success ||
MLPreprocessingHelper.GetJobStatus(status) is "error" or "failed" or "cancelled" or
"canceled" or "deadletter" or "dead-lettered" or "deadlettered" or "dead_letter" or "dead-letter")
{
try
{
await RequestAsync("logs", () => client.PreprocessingClient.LogAsync(
modelId, jobId, computeSize, ApiTimeout, cancellationToken));
}
catch (Exception) when (!cancellationToken.IsCancellationRequested) { /* Preserve the job error. */ }
throw new InvalidOperationException($"Preprocessing job {jobId} failed: {JsonSerializer.Serialize(status, status.GetType())}");
}
if (MLPreprocessingHelper.GetJobStatus(status) is "success" or "succeeded" or "completed")
break;
TimeSpan remaining = statusDeadline - DateTimeOffset.UtcNow;
if (remaining > TimeSpan.Zero)
await Task.Delay(remaining < pollingInterval ? remaining : pollingInterval, cancellationToken);
}

// 5. Retrieve logs; stop after the first successful response.
try
{
await RequestAsync("logs", () => client.PreprocessingClient.LogAsync(
modelId, jobId, computeSize, ApiTimeout, cancellationToken), maximumAttempts: 10);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested && IsTransient(exception))
{
// A transient logs failure must not prevent result retrieval.
}

// 6. Retrieve and save the original result.
JsonElement result = await RequestJsonAsync("result", () => client.PreprocessingClient.ResultAsync(
modelId: modelId, jobId: jobId, computeSize: computeSize, inputEncryptionKey: encryptionKey,
timeout: ApiTimeout, cancellationToken: cancellationToken),
maximumAttempts: int.MaxValue, retryDeadline: DateTimeOffset.UtcNow.AddMinutes(5));

// 7. Extract and download every declared artifact.
List<PreprocessingArtifactCacheEntry> artifacts = new();
int artifactIndex = 0;
foreach (string artifactPath in MLPreprocessingHelper.GetArtifactPaths(result))
{
artifactIndex++;
JsonElement extractResponse = await RequestJsonAsync($"extract-{artifactIndex:000}", () =>
client.PreprocessingClient.ExtractAsync(modelId: modelId, jobId: jobId,
fileName: artifactPath, computeSize: computeSize, inputEncryptionKey: encryptionKey,
outputEncryptionKey: encryptionKey, timeout: ApiTimeout,
cancellationToken: cancellationToken), maximumAttempts: 5);
Guid blobId = MLPreprocessingHelper.GetUploadedBlobId(extractResponse);
byte[] bytes = await RequestAsync($"download-{artifactIndex:000}", () =>
client.PreprocessingClient.DownloadBytesAsync(modelId: modelId, jobId: jobId,
blobId: blobId, computeSize: computeSize, inputEncryptionKey: encryptionKey,
timeout: ApiTimeout, cancellationToken: cancellationToken), maximumAttempts: 5, saveJson: false);
await SharedArtifactHelper.SaveAsync(outputDirectory, artifactIndex, artifactPath, bytes, cancellationToken);
artifacts.Add(new PreprocessingArtifactCacheEntry(artifactPath, blobId));
}
cacheEntries.Add(new PreprocessingCacheEntry(datasetName, selectionName, impute, name,
artifact.Partition, artifact.BlobId, jobId, runId,
artifacts.OrderBy(entry => entry.ArtifactPath, StringComparer.Ordinal).ToArray()));

// Local execution helpers retain this partition's output path and numbering.
async Task<JsonElement> RequestJsonAsync<T>(string stage, Func<Task<T>> request,
int maximumAttempts = 1, DateTimeOffset? retryDeadline = null)
{
T response = await RequestAsync(stage, request, maximumAttempts, retryDeadline: retryDeadline);
return JsonSerializer.SerializeToElement(response, response is null ? typeof(T) : response.GetType());
}
string NextFileName(string stage, string extension = "json") =>
$"{++responseFileNumber:000}-{stage}.{extension}";

async Task<T> RequestAsync<T>(string stage, Func<Task<T>> request,
int maximumAttempts = 1, bool saveJson = true, DateTimeOffset? retryDeadline = null)
{
for (int attempt = 1; ; attempt++)
{
T response;
try
{
response = await request();
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
await SharedResponseHelper.SaveExceptionAsync(outputDirectory,
NextFileName($"{stage}-attempt-{attempt:000}-error", "txt"), exception, cancellationToken);
if (attempt >= maximumAttempts || !IsTransient(exception) ||
(retryDeadline.HasValue && DateTimeOffset.UtcNow >= retryDeadline.Value))
throw;
TimeSpan delay = pollingInterval;
if (retryDeadline.HasValue)
{
TimeSpan remaining = retryDeadline.Value - DateTimeOffset.UtcNow;
if (remaining <= TimeSpan.Zero)
throw;
if (remaining < delay)
delay = remaining;
}
await Task.Delay(delay, cancellationToken);
if (retryDeadline.HasValue && DateTimeOffset.UtcNow >= retryDeadline.Value)
throw;
continue;
}
if (saveJson)
await SharedResponseHelper.SaveAsync(outputDirectory, NextFileName(stage), response, cancellationToken);
return response;
}
}

static bool IsTransient(Exception exception) => exception is ParallelModelApiException apiException
? (int)apiException.StatusCode == 404
? !(apiException.Detail ?? string.Empty).Contains("job failed", StringComparison.OrdinalIgnoreCase)
: (int)apiException.StatusCode is 408 or 409 or 429 or >= 500
: exception is System.Net.Http.HttpRequestException or TimeoutException or TaskCanceledException;

}

// 8. Publish both partitions atomically only after both complete.
await SharedCacheHelper.UpdateAsync<List<PreprocessingCacheEntry>>(cacheDirectory,
PreprocessingCacheEntry.NumericalFileName, existingEntries =>
{
List<PreprocessingCacheEntry> entries = existingEntries ?? new();
entries.RemoveAll(entry => string.Equals(entry.Dataset, datasetName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(entry.ModelSelection, selectionName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(entry.Impute, impute, StringComparison.OrdinalIgnoreCase) &&
string.Equals(entry.Algorithm, name, StringComparison.OrdinalIgnoreCase));
entries.AddRange(cacheEntries);
return entries.OrderBy(entry => entry.Dataset, StringComparer.Ordinal)
.ThenBy(entry => entry.ModelSelection, StringComparer.Ordinal)
.ThenBy(entry => entry.Impute, StringComparer.Ordinal)
.ThenBy(entry => entry.Algorithm, StringComparer.Ordinal)
.ThenBy(entry => entry.Partition, StringComparer.Ordinal).ToList();
}, cancellationToken);
}

private static ParallelModelPreprocessingOutputModel CreatePreprocessingOutput(
string algorithm, string imputeArtifact) => new()
{
Name = $"preprocessing-{algorithm}-{Path.GetFileNameWithoutExtension(imputeArtifact)}.zip",
Description = $"Preprocessing {algorithm} on Impute artifact {imputeArtifact}",
RecordType = "Generic",
AccessTier = "Hot",
Tags = new List<string> { "preprocessing", "impute", "integration-tests", algorithm }
};

private static async Task<ParallelModelPreprocessingSendResponseModel> SendPreprocessingAsync(
string algorithm, ParallelModelClient client, Guid modelId,
MLPreprocessingHelper.PreprocessingInput input, string computeSize, string encryptionKey,
string outputDirectory, string requestFileName, CancellationToken token)
{
List<string> numeric = input.NumericColumns.ToList();
List<string> changing = input.VaryingColumns.ToList();
List<string> positive = input.NonNegativeColumns.ToList();
List<string> discrete = input.DiscreteColumns.ToList();
string? target = input.TargetColumn;
string format = input.FileFormat;
Guid blob = input.BlobId;
switch (algorithm)
{
case "FunctionTransformer":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new FunctionTransformerJobSendRequestModel
{
Input = new FunctionTransformerJobSendRequestModel.FunctionTransformerInputModel
{
InputBlobId = blob,
PreprocessorType = "FunctionTransformer",
PreprocessorParams = new FunctionTransformerJobSendRequestModel.FunctionTransformerParams
{
Func = "log1p",
InverseFunc = "expm1"
},
FeatureColumns = positive,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "KBinsDiscretizer":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new KBinsDiscretizerJobSendRequestModel
{
Input = new KBinsDiscretizerJobSendRequestModel.KBinsDiscretizerInputModel
{
InputBlobId = blob,
PreprocessorType = "KBinsDiscretizer",
PreprocessorParams = new KBinsDiscretizerJobSendRequestModel.KBinsDiscretizerParams
{
NBins = 3,
RandomState = 42
},
FeatureColumns = changing,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "label_binarize":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new LabelBinarizeJobSendRequestModel
{
Input = new LabelBinarizeJobSendRequestModel.LabelBinarizeInputModel
{
InputBlobId = blob,
PreprocessorType = "label_binarize",
PreprocessorParams = new LabelBinarizeJobSendRequestModel.LabelBinarizeParams
{
Classes = input.TargetClasses.ToList()
},
FeatureColumns = new List<string>(),
FileFormat = format,
TargetColumn = target!,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "normalize":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new NormalizeJobSendRequestModel
{
Input = new NormalizeJobSendRequestModel.NormalizeInputModel
{
InputBlobId = blob,
PreprocessorType = "normalize",
PreprocessorParams = new NormalizeJobSendRequestModel.NormalizeParams
{
ReturnNorm = false
},
FeatureColumns = numeric,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "OneHotEncoder":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new OneHotEncoderJobSendRequestModel
{
Input = new OneHotEncoderJobSendRequestModel.OneHotEncoderInputModel
{
InputBlobId = blob,
PreprocessorType = "OneHotEncoder",
PreprocessorParams = new OneHotEncoderJobSendRequestModel.OneHotEncoderParams
{
HandleUnknown = "ignore"
},
FeatureColumns = discrete,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "QuantileTransformer":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new QuantileTransformerJobSendRequestModel
{
Input = new QuantileTransformerJobSendRequestModel.QuantileTransformerInputModel
{
InputBlobId = blob,
PreprocessorType = "QuantileTransformer",
PreprocessorParams = new QuantileTransformerJobSendRequestModel.QuantileTransformerParams
{
NQuantiles = Math.Min(20, input.RowCount),
RandomState = 42
},
FeatureColumns = numeric,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);

case "StandardScaler":
return await SendTypedPreprocessingAsync(client, modelId, outputDirectory, requestFileName,
new StandardScalerJobSendRequestModel
{
Input = new StandardScalerJobSendRequestModel.StandardScalerInputModel
{
InputBlobId = blob,
PreprocessorType = "StandardScaler",
PreprocessorParams = new StandardScalerJobSendRequestModel.StandardScalerParams(),
FeatureColumns = numeric,
FileFormat = format,
TargetColumn = target,
KeepOtherColumns = true,
GenerateGraphs = false
},
Output = CreatePreprocessingOutput(algorithm, input.ArtifactPath),
RequestTimeoutSeconds = 300
}, computeSize, encryptionKey, token);
default:
throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm,
"Unsupported preprocessing algorithm in integration test.");
}
}

private static async Task<ParallelModelPreprocessingSendResponseModel> SendTypedPreprocessingAsync<TRequest>(
ParallelModelClient client, Guid modelId, string outputDirectory, string requestFileName,
TRequest request, string computeSize, string key, CancellationToken token)
where TRequest : class, IParallelModelPreprocessingSendRequest
{
await SharedResponseHelper.SaveAsync(outputDirectory, requestFileName, request, token);
return await client.PreprocessingClient.SendAsync(modelId, request, computeSize, key, key, ApiTimeout, token);
}
}