Skip to main content

Random Projection

Original integration-test class: RandomProjection in 7.1.ML.RandomProjection.cs. This is a direct SDK operation, not a PipelineClient workflow.

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

Execution workflow​

  1. Initialise the client and output paths.
  2. Resolve training input and common feature metadata from the held-out partition.
  3. Save and send the concrete request once.
  4. Save each status response until the job reaches a terminal state.
  5. Retrieve logs once after terminal success.
  6. Retrieve the original result.
  7. Extract and download the result and all declared artifacts.
  8. Replace this case atomically after all downloads succeed.

Recorded operation examples​

OperationRecorded jobsResult recorded
GaussianRandomProjection2222
SparseRandomProjection2222

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

Full C# source​

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

Run(string dataset, string modelselection, string impute, string preprocessing, string randomProjectionAlgorithm)
using ParallelModel.Sdk.Authentication;
using ParallelModel.Sdk.Exceptions;
using ParallelModel.Sdk.ML.RandomProjection.Models.Requests;
using ParallelModel.Sdk.UnitTests.Attributes;
using ParallelModel.Sdk.UnitTests.Cache;
using ParallelModel.Sdk.UnitTests.Helpers;
using System.Text.Json;
using static ParallelModel.Sdk.UnitTests.Helpers.MLRandomProjectionHelper;

namespace ParallelModel.Sdk.UnitTests
{
[Collection("RandomProjection")]
public sealed class RandomProjection
{
private static readonly TimeSpan ApiTimeout = TimeSpan.FromSeconds(300);
private static readonly SharedSendThrottle SendThrottle = new(TimeSpan.FromSeconds(12));
private static readonly string[] Algorithms = ["GaussianRandomProjection", "SparseRandomProjection"];

public static TheoryData<string, string, string, string, string> RandomProjectionRequests =>
PreprocessingAttribute.GetRequests(typeof(RandomProjection), nameof(Run), AlgorithmsFor);

private static string[] AlgorithmsFor(string dataset, string preprocessing) => (dataset, preprocessing) switch
{
(_, "label_binarize") => [],
("LoadDiabetes" or "MakeRegression" or "LoadBreastCancer" or "LoadWine" or "MakeClassification",
"StandardScaler" or "FunctionTransformer" or "KBinsDiscretizer" or "normalize" or "QuantileTransformer") => Algorithms,
_ => []
};

[Theory]
[MemberData(nameof(RandomProjectionRequests))]
[Trait("Category", "Integration")]
[Preprocessing(dataset: "LoadDiabetes", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "StandardScaler")]
[Preprocessing(dataset: "LoadDiabetes", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "KBinsDiscretizer")]
[Preprocessing(dataset: "LoadDiabetes", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "normalize")]
[Preprocessing(dataset: "LoadDiabetes", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "QuantileTransformer")]
[Preprocessing(dataset: "MakeRegression", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "StandardScaler")]
[Preprocessing(dataset: "MakeRegression", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "KBinsDiscretizer")]
[Preprocessing(dataset: "MakeRegression", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "normalize")]
[Preprocessing(dataset: "MakeRegression", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "QuantileTransformer")]
[Preprocessing(dataset: "LoadBreastCancer", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "StandardScaler")]
[Preprocessing(dataset: "LoadBreastCancer", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "FunctionTransformer")]
[Preprocessing(dataset: "LoadBreastCancer", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "KBinsDiscretizer")]
[Preprocessing(dataset: "LoadBreastCancer", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "normalize")]
[Preprocessing(dataset: "LoadBreastCancer", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "QuantileTransformer")]
[Preprocessing(dataset: "LoadWine", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "StandardScaler")]
[Preprocessing(dataset: "LoadWine", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "FunctionTransformer")]
[Preprocessing(dataset: "LoadWine", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "KBinsDiscretizer")]
[Preprocessing(dataset: "LoadWine", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "normalize")]
[Preprocessing(dataset: "LoadWine", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "QuantileTransformer")]
[Preprocessing(dataset: "MakeClassification", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "StandardScaler")]
[Preprocessing(dataset: "MakeClassification", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "KBinsDiscretizer")]
[Preprocessing(dataset: "MakeClassification", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "normalize")]
[Preprocessing(dataset: "MakeClassification", modelselection: "TrainTestSplit", impute: "SimpleImputer", preprocessing: "QuantileTransformer")]
public async Task Run(string dataset, string modelselection, string impute, string preprocessing,
string randomProjectionAlgorithm)
{
// 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 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 = ApiTimeout,
AutoRefreshToken = true,
RefreshBeforeExpiry = TimeSpan.FromMinutes(2),
RetryOnUnauthorized = true,
MaxRetries = 3
});

string outputRoot = SharedEnvironmentHelper.OutputDirectory;
string runId = Guid.NewGuid().ToString("N");
string outputDirectory = Path.Combine(outputRoot, "random-projection",
$"{dataset}-{modelselection}-{impute}-{preprocessing}", randomProjectionAlgorithm, runId);
string cacheDirectory = SharedEnvironmentHelper.CacheDirectory;
Directory.CreateDirectory(Path.Combine(outputDirectory, "artifacts"));
int responseFileNumber = 0;

// 2. Resolve training input and common feature metadata from the held-out partition.
// Only the training blob is submitted; the worker performs its own evaluation split.
(TransformedInput train, TransformedInput test) = await LoadInputsAsync(
cacheDirectory, dataset, modelselection, impute, preprocessing, cancellationToken);
async Task<string[]> ReadColumnsAsync(TransformedInput entry)
{
byte[] bytes = await RequestAsync($"read-{entry.Partition}", () =>
parallelModelClient.PreprocessingClient.DownloadBytesAsync(modelId: modelId, jobId: entry.JobId,
blobId: entry.BlobId, computeSize: computeSize, inputEncryptionKey: encryptionKey,
timeout: ApiTimeout, cancellationToken: cancellationToken),
maximumAttempts: 5, saveJson: false);
return ReadHeader(bytes, entry.Partition);
}
string[] features = ResolveColumns(await ReadColumnsAsync(train), await ReadColumnsAsync(test));
int componentCount = Math.Max(1, Math.Min(8, features.Length / 2));
JsonElement componentCountJson = JsonSerializer.SerializeToElement(componentCount);

// 3. Save and send the concrete request once.
await SendThrottle.WaitForSendSlotAsync(cancellationToken);
string requestFileName = $"{++responseFileNumber:000}-request.json";
JsonElement sent = await RequestAsync("send", () => SendRandomProjectionAsync(parallelModelClient, modelId,
computeSize, encryptionKey, train.BlobId, features, componentCountJson, dataset,
$"{dataset}-{modelselection}-{impute}-{preprocessing}-{randomProjectionAlgorithm}.zip",
preprocessing, randomProjectionAlgorithm, outputDirectory, requestFileName, cancellationToken));
Guid jobId = RequiredProperty(sent, "jobId", "job_id").GetGuid();

// 4. Save each status response until the job reaches a terminal state.
DateTimeOffset statusDeadline = DateTimeOffset.UtcNow.AddMinutes(10);
for (int attempt = 1; ; attempt++)
{
JsonElement statusResponse = await RequestAsync($"status-{attempt:000}", () =>
parallelModelClient.RandomProjectionClient.StatusAsync(
modelId, jobId, computeSize, ApiTimeout, cancellationToken),
maximumAttempts: 5, retryDeadline: statusDeadline);
JsonElement statusValue = RequiredProperty(statusResponse, "status");
string? jobStatus = statusValue.ValueKind == JsonValueKind.String ? statusValue.GetString() : null;
switch (jobStatus?.ToLowerInvariant())
{
case "success" or "succeeded" or "completed":
break;
case null or "error" or "failed" or "cancelled" or "canceled" or "deadletter"
or "dead-lettered" or "deadlettered" or "dead_letter" or "dead-letter":
try
{
await RequestAsync("logs", GetLogsAsync);
}
catch (Exception) when (!cancellationToken.IsCancellationRequested)
{
// RequestAsync has already attempted to save the log error.
}

throw new InvalidOperationException(
$"Job {jobId} returned a status error or ended with status '{jobStatus}'. See saved responses.");
default:
if (DateTimeOffset.UtcNow >= statusDeadline)
throw new TimeoutException($"Status polling expired for job {jobId}.");
await Task.Delay(pollingInterval, cancellationToken);
continue;
}

break;
}

// 5. Retrieve logs once after terminal success.
try
{
await RequestAsync("logs", GetLogsAsync);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested && (exception switch
{
ParallelModelApiException error => (int)error.StatusCode is 408 or 409 or 429 or >= 500 ||
((int)error.StatusCode == 404 && error.Detail?.Contains("job failed", StringComparison.OrdinalIgnoreCase) != true),
HttpRequestException or TimeoutException or TaskCanceledException => true,
_ => false
}))
{ /* The optional log request error was saved. */
}

// 6. Retrieve the original result.
JsonElement result = await RequestAsync("result", () => parallelModelClient.RandomProjectionClient.ResultAsync(
modelId, jobId, computeSize, encryptionKey, timeout: ApiTimeout, cancellationToken: cancellationToken),
maximumAttempts: int.MaxValue, retryDeadline: DateTimeOffset.UtcNow.AddMinutes(5));

// 7. Extract and download the result and all declared artifacts.
string[] paths = ArtifactPaths(result).Distinct(StringComparer.Ordinal).ToArray();
// The original RandomProjection test explicitly extracts these two artifacts.
// Prefer the actual result's declared list whenever it is supplied.
if (paths.Length == 0)
paths = ["model.joblib", "result.json"];
List<RandomProjectionCacheEntry> outputs = new();
for (int index = 0; index < paths.Length; index++)
{
string path = paths[index];
JsonElement extracted = await RequestAsync("extract", () => parallelModelClient.RandomProjectionClient.ExtractAsync(
modelId, jobId, path, computeSize, encryptionKey, encryptionKey, timeout: ApiTimeout,
cancellationToken: cancellationToken), maximumAttempts: 5);
Guid blobId = RequiredProperty(extracted, "uploadedBlobId", "uploaded_blob_id").GetGuid();
byte[] bytes = await RequestAsync("download", () => parallelModelClient.RandomProjectionClient.DownloadBytesAsync(
modelId, jobId, blobId, computeSize, encryptionKey, ApiTimeout, cancellationToken),
maximumAttempts: 5, saveJson: false);
await SharedArtifactHelper.SaveAsync(outputDirectory, index + 1, path, bytes, cancellationToken);
// One submitted input produced this archive; no held-out test output is created.
outputs.Add(new(dataset, modelselection, impute, preprocessing, randomProjectionAlgorithm,
train.Partition, blobId, path, train.BlobId, train.BlobId, train.ImputedBlobId,
train.BlobId, jobId, runId));
}

// 8. Replace this case atomically after all downloads succeed.
await SharedCacheHelper.UpdateAsync<List<RandomProjectionCacheEntry>>(cacheDirectory, RandomProjectionCacheEntry.FileName, current =>
{
current ??= new();
current.RemoveAll(entry => entry.Matches(dataset, modelselection, impute, preprocessing, randomProjectionAlgorithm));
current.AddRange(outputs);
return current.OrderBy(entry => entry.Dataset, StringComparer.Ordinal)
.ThenBy(entry => entry.Modelselection, StringComparer.Ordinal)
.ThenBy(entry => entry.Impute, StringComparer.Ordinal)
.ThenBy(entry => entry.Preprocessing, StringComparer.Ordinal)
.ThenBy(entry => entry.Randomprojectionalgo, StringComparer.Ordinal)
.ThenBy(entry => entry.Partition, StringComparer.Ordinal)
.ThenBy(entry => entry.ArtifactPath, StringComparer.Ordinal).ToList();
}, cancellationToken);

Task<JsonElement> GetLogsAsync() => parallelModelClient.RandomProjectionClient.LogAsync(
modelId, jobId, computeSize, TimeSpan.FromSeconds(30), cancellationToken);

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++)
{
cancellationToken.ThrowIfCancellationRequested();
T response;
try
{
response = await request();
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
{
await SharedResponseHelper.SaveExceptionAsync(outputDirectory,
$"{++responseFileNumber:000}-{stage}-attempt-{attempt:000}-error.txt",
exception, cancellationToken);
bool transient = exception switch
{
ParallelModelApiException error => (int)error.StatusCode is 408 or 409 or 429 or >= 500 ||
((int)error.StatusCode == 404 && error.Detail?.Contains("job failed", StringComparison.OrdinalIgnoreCase) != true),
HttpRequestException or TimeoutException or TaskCanceledException => true,
_ => false
};
if (attempt >= maximumAttempts || !transient ||
(retryDeadline.HasValue && DateTimeOffset.UtcNow + pollingInterval >= retryDeadline.Value))
throw;
await Task.Delay(pollingInterval, cancellationToken);
continue;
}

if (saveJson)
await SharedResponseHelper.SaveAsync(outputDirectory,
$"{++responseFileNumber:000}-{stage}.json", response, cancellationToken);
return response;
}
}
}

private static async Task<JsonElement> SendRandomProjectionAsync(ParallelModelClient parallelModelClient, Guid modelId,
string computeSize, string encryptionKey, Guid trainBlobId, string[] featureColumns,
JsonElement componentCountJson, string dataset, string outputName, string preprocessing, string randomProjectionAlgorithm,
string outputDirectory, string requestFileName, CancellationToken cancellationToken)
{
ParallelModelRandomProjectionOutputModel parallelModelRandomProjectionOutputModel = new()
{
Name = outputName,
Description = "RandomProjection integration test using cached numerical preprocessing outputs",
RecordType = "Generic",
AccessTier = "Hot",
Tags = ["random-projection", dataset, preprocessing, randomProjectionAlgorithm]
};

async Task<JsonElement> SendTypedAsync<TRequest>(TRequest randomProjectionJobSendRequestModel)
where TRequest : class, IParallelModelRandomProjectionSendRequest
{
await SharedResponseHelper.SaveAsync(outputDirectory, requestFileName, randomProjectionJobSendRequestModel, cancellationToken);
return await parallelModelClient.RandomProjectionClient.SendAsync(modelId, randomProjectionJobSendRequestModel,
computeSize, encryptionKey, encryptionKey, ApiTimeout, cancellationToken);
}

return randomProjectionAlgorithm switch
{
"GaussianRandomProjection" => await SendTypedAsync(new GaussianRandomProjectionJobSendRequestModel
{
Input = new GaussianRandomProjectionJobSendRequestModel.GaussianRandomProjectionInputModel
{
InputBlobId = trainBlobId,
ClassifierType = "GaussianRandomProjection",
ClassifierParams = new GaussianRandomProjectionJobSendRequestModel.GaussianRandomProjectionParamsModel
{
NComponents = componentCountJson,
Eps = 0.5,
ComputeInverseComponents = true,
RandomState = 42
},
DataType = "numeric",
FeatureColumns = featureColumns.ToList(),
FileFormat = "csv",
Evaluation = new GaussianRandomProjectionJobSendRequestModel.GaussianRandomProjectionEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = parallelModelRandomProjectionOutputModel,
RequestTimeoutSeconds = 300
}),
"SparseRandomProjection" => await SendTypedAsync(new SparseRandomProjectionJobSendRequestModel
{
Input = new SparseRandomProjectionJobSendRequestModel.SparseRandomProjectionInputModel
{
InputBlobId = trainBlobId,
ClassifierType = "SparseRandomProjection",
ClassifierParams = new SparseRandomProjectionJobSendRequestModel.SparseRandomProjectionParamsModel
{
NComponents = componentCountJson,
Eps = 0.5,
Density = "auto",
DenseOutput = false,
RandomState = 42
},
DataType = "numeric",
FeatureColumns = featureColumns.ToList(),
FileFormat = "csv",
Evaluation = new SparseRandomProjectionJobSendRequestModel.SparseRandomProjectionEvaluationModel
{
TestSize = 0.2,
RandomState = 42,
Shuffle = true
},
GenerateGraphs = true
},
Output = parallelModelRandomProjectionOutputModel,
RequestTimeoutSeconds = 300
}),
_ => throw new NotSupportedException(randomProjectionAlgorithm)
};
}
}
}