Clustering
Original integration-test class: Cluster in 6.11.ML.Cluster.cs. This is a direct SDK operation, not a PipelineClient workflow.
8 recorded job or prediction directories matched by module and scenario path. 0 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
| Client | Methods in the source |
|---|---|
ClusterClient | DownloadBytesAsync, ExtractAsync, LogAsync, ResultAsync, SendAsync, StatusAsync |
Execution workflow
- Initialise the client and output paths.
- Resolve only the transformed text blobs required by this algorithm.
- Save and send the concrete request once.
- Save each status response until the job reaches a terminal state.
- Retrieve logs once after terminal success.
- Retrieve the original result.
- Extract and download the result and all declared artifacts.
- Replace this case atomically after all downloads succeed.
Recorded operation examples
| Operation | Recorded jobs | Result recorded |
|---|---|---|
| AffinityPropagation | 1 | 0 |
| AgglomerativeClustering | 1 | 0 |
| Birch | 1 | 0 |
| BisectingKMeans | 1 | 0 |
| DBSCAN | 1 | 0 |
| HDBSCAN | 1 | 0 |
| MeanShift | 1 | 0 |
| SpectralClustering | 1 | 0 |
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.Cluster.Run"
Full C# source
The supplied test logic is preserved. The method signature is:
Run(string dataset, string modelselection, string impute, string preprocessing, string clusterAlgorithm)
using ParallelModel.Sdk.Authentication;
using ParallelModel.Sdk.Exceptions;
using ParallelModel.Sdk.ML.Cluster.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.MLClusterHelper;
namespace ParallelModel.Sdk.UnitTests
{
[Collection("Cluster")]
public sealed class Cluster
{
private static readonly TimeSpan ApiTimeout = TimeSpan.FromSeconds(300);
private static readonly SharedSendThrottle SendThrottle = new(TimeSpan.FromSeconds(12));
private static readonly string[] Algorithms =
[
"AffinityPropagation", "AgglomerativeClustering", "Birch", "BisectingKMeans",
"DBSCAN", "HDBSCAN", "KMeans", "MeanShift", "MiniBatchKMeans", "OPTICS",
"SpectralClustering"
];
public static TheoryData<string, string, string, string, string> ClusterRequests =>
PreprocessingAttribute.GetRequests(typeof(Cluster), nameof(Run), AlgorithmsFor);
private static string[] AlgorithmsFor(string dataset, string preprocessing) => dataset switch
{
"Fetch20Newsgroups" => Algorithms,
_ => []
};
[Theory]
[MemberData(nameof(ClusterRequests))]
[Trait("Category", "Integration")]
[Preprocessing(dataset: "Fetch20Newsgroups", modelselection: "TrainTestSplit",
impute: "SimpleImputer", preprocessing: "label_binarize")]
public async Task Run(string dataset, string modelselection, string impute, string preprocessing,
string clusterAlgorithm)
{
// 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, "cluster",
$"{dataset}-{modelselection}-{impute}-{preprocessing}", clusterAlgorithm, runId);
string cacheDirectory = SharedEnvironmentHelper.CacheDirectory;
Directory.CreateDirectory(Path.Combine(outputDirectory, "artifacts"));
int responseFileNumber = 0;
// 2. Resolve only the transformed text blobs required by this algorithm.
bool requiresTest = clusterAlgorithm is not ("AgglomerativeClustering" or "DBSCAN"
or "HDBSCAN" or "OPTICS" or "SpectralClustering");
(TransformedInput train, TransformedInput? test) = await LoadInputsAsync(
cacheDirectory, dataset, modelselection, impute, preprocessing, requiresTest, cancellationToken);
const string textColumn = "text";
// 3. Save and send the concrete request once.
await SendThrottle.WaitForSendSlotAsync(cancellationToken);
string requestFileName = $"{++responseFileNumber:000}-request.json";
JsonElement sent = await RequestAsync("send", () => SendClusterAsync(parallelModelClient, modelId,
computeSize, encryptionKey, train.BlobId, test?.BlobId, textColumn, dataset, modelselection, impute,
$"{dataset}-{modelselection}-{impute}-{preprocessing}-{clusterAlgorithm}.zip",
preprocessing, clusterAlgorithm, 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.ClusterClient.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.ClusterClient.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();
// Preserve the original result.json fallback when no artifact list is supplied.
if (paths.Length == 0)
paths = ["result.json"];
List<ClusterCacheEntry> outputs = new();
for (int index = 0; index < paths.Length; index++)
{
string path = paths[index];
JsonElement extracted = await RequestAsync("extract", () => parallelModelClient.ClusterClient.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.ClusterClient.DownloadBytesAsync(
modelId, jobId, blobId, computeSize, encryptionKey, ApiTimeout, cancellationToken),
maximumAttempts: 5, saveJson: false);
await SharedArtifactHelper.SaveAsync(outputDirectory, index + 1, path, bytes, cancellationToken);
outputs.Add(new(dataset, modelselection, impute, preprocessing, clusterAlgorithm,
"train", blobId, path, train.BlobId, train.BlobId, test?.BlobId, jobId, runId));
if (test is not null)
outputs.Add(new(dataset, modelselection, impute, preprocessing, clusterAlgorithm,
"test", blobId, path, test.BlobId, train.BlobId, test.BlobId, jobId, runId));
}
// 8. Replace this case atomically after all downloads succeed.
await SharedCacheHelper.UpdateAsync<List<ClusterCacheEntry>>(cacheDirectory, ClusterCacheEntry.FileName, current =>
{
current ??= new();
current.RemoveAll(entry => entry.Matches(dataset, modelselection, impute, preprocessing, clusterAlgorithm));
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.Clusteralgo, StringComparer.Ordinal)
.ThenBy(entry => entry.Partition, StringComparer.Ordinal)
.ThenBy(entry => entry.ArtifactPath, StringComparer.Ordinal).ToList();
}, cancellationToken);
Task<JsonElement> GetLogsAsync() => parallelModelClient.ClusterClient.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> SendClusterAsync(ParallelModelClient parallelModelClient, Guid modelId,
string computeSize, string encryptionKey, Guid trainBlobId, Guid? testBlobId, string textColumn,
string dataset, string modelselection, string impute, string outputName, string preprocessing,
string clusterAlgorithm, string outputDirectory, string requestFileName, CancellationToken cancellationToken)
{
ParallelModelClusterOutputModel parallelModelClusterOutputModel = new()
{
Name = outputName,
Description = "Cluster integration test using cached text preprocessing outputs",
RecordType = "Generic",
AccessTier = "Hot",
Tags = ["cluster", dataset, modelselection, impute, preprocessing, clusterAlgorithm]
};
async Task<JsonElement> SendTypedAsync<TRequest>(TRequest clusterJobSendRequestModel)
where TRequest : class, IParallelModelClusterSendRequest
{
await SharedResponseHelper.SaveAsync(outputDirectory, requestFileName,
clusterJobSendRequestModel, cancellationToken);
return testBlobId.HasValue
? await parallelModelClient.ClusterClient.SendAsync(modelId, clusterJobSendRequestModel,
computeSize, encryptionKey, encryptionKey, encryptionKey, ApiTimeout, cancellationToken)
: await parallelModelClient.ClusterClient.SendAsync(modelId, clusterJobSendRequestModel,
computeSize, encryptionKey, encryptionKey, ApiTimeout, cancellationToken);
}
return clusterAlgorithm switch
{
"AffinityPropagation" => await SendTypedAsync(new AffinityPropagationJobSendRequestModel
{
Input = new AffinityPropagationJobSendRequestModel.AffinityPropagationInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "AffinityPropagation",
ClassifierParams = new AffinityPropagationJobSendRequestModel.AffinityPropagationClassifierParamsModel { Damping = 0.75, MaxIter = 200 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new AffinityPropagationJobSendRequestModel.AffinityPropagationVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"AgglomerativeClustering" => await SendTypedAsync(new AgglomerativeClusteringJobSendRequestModel
{
Input = new AgglomerativeClusteringJobSendRequestModel.AgglomerativeClusteringInputModel
{
TrainBlobId = trainBlobId,
ClassifierType = "AgglomerativeClustering",
ClassifierParams = new AgglomerativeClusteringJobSendRequestModel.AgglomerativeClusteringClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new AgglomerativeClusteringJobSendRequestModel.AgglomerativeClusteringVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"Birch" => await SendTypedAsync(new BirchJobSendRequestModel
{
Input = new BirchJobSendRequestModel.BirchInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "Birch",
ClassifierParams = new BirchJobSendRequestModel.BirchClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new BirchJobSendRequestModel.BirchVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"BisectingKMeans" => await SendTypedAsync(new BisectingKMeansJobSendRequestModel
{
Input = new BisectingKMeansJobSendRequestModel.BisectingKMeansInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "BisectingKMeans",
ClassifierParams = new BisectingKMeansJobSendRequestModel.BisectingKMeansClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new BisectingKMeansJobSendRequestModel.BisectingKMeansVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"DBSCAN" => await SendTypedAsync(new DBSCANJobSendRequestModel
{
Input = new DBSCANJobSendRequestModel.DBSCANInputModel
{
TrainBlobId = trainBlobId,
ClassifierType = "DBSCAN",
ClassifierParams = new DBSCANJobSendRequestModel.DBSCANClassifierParamsModel { Eps = 0.42, MinSamples = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new DBSCANJobSendRequestModel.DBSCANVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"HDBSCAN" => await SendTypedAsync(new HDBSCANJobSendRequestModel
{
Input = new HDBSCANJobSendRequestModel.HDBSCANInputModel
{
TrainBlobId = trainBlobId,
ClassifierType = "HDBSCAN",
ClassifierParams = new HDBSCANJobSendRequestModel.HDBSCANClassifierParamsModel { MinClusterSize = 3, MinSamples = 2 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new HDBSCANJobSendRequestModel.HDBSCANVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"KMeans" => await SendTypedAsync(new KMeansJobSendRequestModel
{
Input = new KMeansJobSendRequestModel.KMeansInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "KMeans",
ClassifierParams = new KMeansJobSendRequestModel.KMeansClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new KMeansJobSendRequestModel.KMeansVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"MeanShift" => await SendTypedAsync(new MeanShiftJobSendRequestModel
{
Input = new MeanShiftJobSendRequestModel.MeanShiftInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "MeanShift",
ClassifierParams = new MeanShiftJobSendRequestModel.MeanShiftClassifierParamsModel { Bandwidth = 0.5, ClusterAll = true },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new MeanShiftJobSendRequestModel.MeanShiftVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"MiniBatchKMeans" => await SendTypedAsync(new MiniBatchKMeansJobSendRequestModel
{
Input = new MiniBatchKMeansJobSendRequestModel.MiniBatchKMeansInputModel
{
TrainBlobId = trainBlobId,
TestBlobId = testBlobId!.Value,
ClassifierType = "MiniBatchKMeans",
ClassifierParams = new MiniBatchKMeansJobSendRequestModel.MiniBatchKMeansClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new MiniBatchKMeansJobSendRequestModel.MiniBatchKMeansVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"OPTICS" => await SendTypedAsync(new OPTICSJobSendRequestModel
{
Input = new OPTICSJobSendRequestModel.OPTICSInputModel
{
TrainBlobId = trainBlobId,
ClassifierType = "OPTICS",
ClassifierParams = new OPTICSJobSendRequestModel.OPTICSClassifierParamsModel { MinSamples = 3, MinClusterSize = 3, Xi = 0.05 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new OPTICSJobSendRequestModel.OPTICSVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
"SpectralClustering" => await SendTypedAsync(new SpectralClusteringJobSendRequestModel
{
Input = new SpectralClusteringJobSendRequestModel.SpectralClusteringInputModel
{
TrainBlobId = trainBlobId,
ClassifierType = "SpectralClustering",
ClassifierParams = new SpectralClusteringJobSendRequestModel.SpectralClusteringClassifierParamsModel { NClusters = 3 },
TextColumn = textColumn,
FileFormat = "csv",
VectorizerParams = new SpectralClusteringJobSendRequestModel.SpectralClusteringVectorizerParamsModel
{
NgramRange = [1, 2],
MinDf = 1,
MaxFeatures = 500
},
SvdComponents = 8,
GenerateGraphs = true
},
Output = parallelModelClusterOutputModel,
RequestTimeoutSeconds = 300
}),
_ => throw new NotSupportedException(clusterAlgorithm)
};
}
}
}