Skip to main content

Text Imputation

Original integration-test class: ImputeText in 3.1.ML.Impute.Text.cs. This is a direct SDK operation, not a PipelineClient workflow.

2 recorded job or prediction directories matched by module and scenario path. 2 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
ImputeClientDownloadBytesAsync, ExtractAsync, LogAsync, ResultAsync, SendAsync, StatusAsync

Execution workflow​

  1. Initialise the client and output paths.
  2. Read the cached dataset metadata and the exact upstream split blobs.
  3. Send the original strongly typed request and save the SDK response.
  4. Poll status and save every response until the job reaches a terminal state.
  5. Retrieve logs once successfully, following ModelSelection.
  6. Retrieve and save the original result response.
  7. Extract and download every artifact returned for this partition.
  8. Atomically replace both partitions after both jobs and downloads complete.

Recorded operation examples​

OperationRecorded jobsResult recorded
SimpleImputer22

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.ImputeText.Run"

Full C# source​

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

Run(string datasetName, string selectionName, string name)
using ParallelModel.Sdk.Authentication;
using ParallelModel.Sdk.Exceptions;
using ParallelModel.Sdk.ML.Impute.Models;
using ParallelModel.Sdk.ML.Impute.Models.Requests;
using ParallelModel.Sdk.UnitTests.Attributes;
using ParallelModel.Sdk.UnitTests.Cache;
using ParallelModel.Sdk.UnitTests.Helpers;
using ParallelModel.Sdk.UnitTests.Models;

namespace ParallelModel.Sdk.UnitTests;

[Collection("Impute")]
public sealed class ImputeText
{
private static readonly SharedSendThrottle sendThrottle = new(TimeSpan.FromSeconds(12));
private static readonly TimeSpan ApiTimeout = TimeSpan.FromSeconds(300);

private static readonly string[] Algorithms = { "SimpleImputer" };

public static TheoryData<string, string, string> ImputeRequests =>
ModelSelectionAttribute.GetRequests(typeof(ImputeText), nameof(Run), ImputeAlgorithmsFor);

private static string[] ImputeAlgorithmsFor(string datasetName) => Algorithms;

[Theory]
[Trait("Category", "Integration")]
[MemberData(nameof(ImputeRequests))]
[ModelSelection("Fetch20Newsgroups", "TrainTestSplit")]
public async Task Run(string datasetName, string selectionName, string name)
{
// 1. Initialise the 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 apiRequestTimeout = ApiTimeout;
TimeSpan pollingInterval = TimeSpan.FromSeconds(30);
ParallelModelClient parallelModelClient = new(new DefaultParallelModelAuthenticationOptions
{
Region = SharedEnvironmentHelper.Required("PARALLELMODEL_REGION"),
ClientId = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_ID"),
ClientSecret = SharedEnvironmentHelper.Required("PARALLELMODEL_CLIENT_SECRET"),
Timeout = TimeSpan.FromSeconds(90)
});

string runId = Guid.NewGuid().ToString("N");
string cacheDirectory = SharedEnvironmentHelper.CacheDirectory;

// 2. Read the cached dataset metadata and the exact upstream split blobs.
DatasetFixture dataset = await MLDatasetHelper.LoadDatasetAsync(datasetName, modelId, cacheDirectory,
cancellationToken);
IReadOnlyList<MLImputeHelper.SelectionArtifact> sources = await MLImputeHelper.LoadSelectionAsync(
datasetName, selectionName, dataset.BlobId, cacheDirectory, cancellationToken);
List<ImputeCacheEntry> cacheEntries = new();

foreach (MLImputeHelper.SelectionArtifact source in sources)
{
string outputDirectory = Path.Combine(SharedEnvironmentHelper.OutputDirectory, "impute.text",
datasetName, selectionName, name, runId, source.Partition);
Directory.CreateDirectory(Path.Combine(outputDirectory, "artifacts"));
int responseFileNumber = 0;

// 3. Send the original strongly typed request and save the SDK response.
await sendThrottle.WaitForSendSlotAsync(cancellationToken);
string requestFileName = NextFileName("request");
ParallelModelImputeSendResponseModel sendResponse = await RequestAsync("send",
() => SendImputeAsync(name, parallelModelClient, modelId, source, dataset,
computeSize, encryptionKey, apiRequestTimeout, outputDirectory,
requestFileName, cancellationToken));
Guid jobId = sendResponse.JobId;

// 4. Poll status and save every response until the job reaches a terminal state.
DateTimeOffset statusDeadline = DateTimeOffset.UtcNow.AddMinutes(10);
for (int attempt = 1; ; attempt++)
{
ParallelModelImputeStatusResponseModel statusResponse = await RequestAsync(
$"status-{attempt:000}", () => parallelModelClient.ImputeClient.StatusAsync(
modelId, jobId, computeSize, apiRequestTimeout, cancellationToken),
maximumAttempts: int.MaxValue, retryDeadline: statusDeadline);
if (statusResponse is not ParallelModelImputeStatusResponseModel.Success status)
throw new InvalidOperationException($"Job {jobId} returned a status API error. See saved response.");
string? jobStatus = status.Status?.ToLowerInvariant();
if (jobStatus is "success" or "succeeded" or "completed")
break;
if (jobStatus 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", () => parallelModelClient.ImputeClient.LogAsync(
modelId, jobId, computeSize, apiRequestTimeout, cancellationToken));
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
exception is not OperationCanceledException)
{
// RequestAsync already saved the error; retain the terminal job failure.
}
throw new InvalidOperationException($"Job {jobId} ended with status '{status.Status}'. See saved response.");
}
if (DateTimeOffset.UtcNow >= statusDeadline)
throw new TimeoutException($"Status polling expired for job {jobId}.");
await Task.Delay(pollingInterval, cancellationToken);
}

// 5. Retrieve logs once successfully, following ModelSelection.
try
{
await RequestAsync("logs", () => parallelModelClient.ImputeClient.LogAsync(
modelId, jobId, computeSize, apiRequestTimeout, cancellationToken), maximumAttempts: 10);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
IsTransient(exception))
{
// Logs may be temporarily unavailable; the result can still be retrieved.
}

// 6. Retrieve and save the original result response.
ParallelModelImputeResultResponseModel result = await RequestAsync("result",
() => parallelModelClient.ImputeClient.ResultAsync(modelId: modelId, jobId: jobId,
computeSize: computeSize, inputEncryptionKey: encryptionKey, timeout: apiRequestTimeout,
cancellationToken: cancellationToken), maximumAttempts: int.MaxValue,
retryDeadline: DateTimeOffset.UtcNow.AddMinutes(5));

// 7. Extract and download every artifact returned for this partition.
IReadOnlyList<string> artifactFiles = MLImputeHelper.GetArtifactPaths(result);
List<ImputeArtifactCacheEntry> artifacts = new();
for (int index = 0; index < artifactFiles.Count; index++)
{
string artifactPath = artifactFiles[index];
ParallelModelImputeExtractResponseModel extractResponse = await RequestAsync(
$"extract-{index + 1:000}", () => parallelModelClient.ImputeClient.ExtractAsync(
modelId: modelId, jobId: jobId, fileName: artifactPath, computeSize: computeSize,
inputEncryptionKey: encryptionKey, outputEncryptionKey: encryptionKey,
timeout: apiRequestTimeout, cancellationToken: cancellationToken), maximumAttempts: 5);
Guid blobId = extractResponse.UploadedBlobId;
byte[] bytes = await RequestAsync($"download-{index + 1:000}",
() => parallelModelClient.ImputeClient.DownloadBytesAsync(
modelId: modelId, jobId: jobId, blobId: blobId, computeSize: computeSize,
inputEncryptionKey: encryptionKey, timeout: apiRequestTimeout,
cancellationToken: cancellationToken), maximumAttempts: 5, saveJson: false);
await SharedArtifactHelper.SaveAsync(outputDirectory, index + 1, artifactPath, bytes, cancellationToken);
artifacts.Add(new ImputeArtifactCacheEntry(artifactPath, blobId));
}
cacheEntries.Add(new ImputeCacheEntry(datasetName, selectionName, name, source.Partition,
source.BlobId, jobId, runId, artifacts.OrderBy(artifact => artifact.ArtifactPath,
StringComparer.Ordinal).ToList()));

// Local request execution, scoped to this partition.
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. Atomically replace both partitions after both jobs and downloads complete.
await SharedCacheHelper.UpdateAsync<List<ImputeCacheEntry>>(cacheDirectory,
ImputeCacheEntry.TextFileName, existingEntries =>
{
List<ImputeCacheEntry> entries = existingEntries ?? new();
entries.RemoveAll(entry => string.Equals(entry.Dataset, datasetName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(entry.ModelSelection, selectionName, 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.Algorithm, StringComparer.Ordinal)
.ThenBy(entry => entry.Partition, StringComparer.Ordinal).ToList();
}, cancellationToken);
}

private static ParallelModelImputeOutputModel CreateImputeOutput(string algorithm, string inputArtifact) => new()
{
Name = $"impute-{algorithm}-{Path.GetFileNameWithoutExtension(inputArtifact)}.zip",
Description = $"Impute {algorithm} on ModelSelection artifact {inputArtifact}",
RecordType = "Generic",
AccessTier = "Hot",
Tags = new List<string> { "impute", "model-selection", "integration-tests", algorithm }
};

private static async Task<ParallelModelImputeSendResponseModel> SendImputeAsync(
string algorithm, ParallelModelClient client, Guid modelId, MLImputeHelper.SelectionArtifact source,
DatasetFixture dataset, string size, string key, TimeSpan timeout,
string outputDirectory, string requestFileName, CancellationToken token)
{
List<string> features = dataset.FeatureColumns.ToList();
string? targetColumn = dataset.TargetColumn;
List<string> missingTokens = new() { "", "NA", "NaN", "nan", "null", "?" };
// Preserve each request's concrete SDK type for serialization.
return algorithm switch
{
"SimpleImputer" => await SendTypedImputeAsync(client, modelId, outputDirectory, requestFileName,
new SimpleImputerJobSendRequestModel
{
Input = new SimpleImputerJobSendRequestModel.SimpleImputerInputModel
{
InputBlobId = source.BlobId,
ClassifierType = "SimpleImputer",
ClassifierParams = new SimpleImputerJobSendRequestModel.SimpleImputerClassifierParamsModel
{
Strategy = "most_frequent",
AddIndicator = false,
KeepEmptyFeatures = true
},
DataType = "categorical",
FeatureColumns = features,
FileFormat = source.FileFormat,
MissingTokens = missingTokens,
TargetColumn = targetColumn!,
KeepOtherColumns = true,
Evaluation = new SimpleImputerJobSendRequestModel.SimpleImputerEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = false
},
Output = CreateImputeOutput("SimpleImputer", source.ArtifactPath),
RequestTimeoutSeconds = 300
}, size, key, timeout, token),
_ => throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm,
"Unsupported Impute algorithm in integration test.")
};
}

private static async Task<ParallelModelImputeSendResponseModel> SendTypedImputeAsync<TRequest>(
ParallelModelClient client, Guid modelId, string outputDirectory, string requestFileName,
TRequest request, string computeSize, string key, TimeSpan timeout, CancellationToken token)
where TRequest : class, IParallelModelImputeSendRequest
{
await SharedResponseHelper.SaveAsync(outputDirectory, requestFileName, request, token);
return await client.ImputeClient.SendAsync(modelId, request, computeSize, key, key, timeout, token);
}
}