diff --git a/demos/analytics-using-managedcleanroom/README-API.md b/demos/analytics-using-managedcleanroom/README-API.md index 59ca823..6c10401 100644 --- a/demos/analytics-using-managedcleanroom/README-API.md +++ b/demos/analytics-using-managedcleanroom/README-API.md @@ -91,6 +91,7 @@ providing your own data and query. - [Appendix D: Dataset Schema Reference](#appendix-d-dataset-schema-reference) - [Appendix E: Query Structure Reference](#appendix-e-query-structure-reference) - [Appendix F: REST API Endpoint Reference](#appendix-f-rest-api-endpoint-reference) +- [Appendix G: Collaboration Management](#appendix-g-collaboration-management) - [Appendix: App-Based Authentication (SPN)](#appendix-app-based-authentication-spn) --- @@ -105,6 +106,7 @@ providing your own data and query. | PowerShell | 7.x+ | | MSAL.PS module | `Install-Module MSAL.PS -Scope CurrentUser -Force` | | azcopy | v10+ (CPK mode only) | +| kubectl | Latest stable | > **Quota check:** This sample deploys an AKS cluster and Confidential ACI > container groups in the `$resourceLocation` region (**West US** by default). Ensure your subscription has the @@ -112,19 +114,30 @@ providing your own data and query. > > | Resource | Minimum vCPUs | SKU / Family | > |---|---|---| -> | AKS node pool | 8 | Standard_D4ds_v5 (Ddsv5 family) | +> | AKS node pool | 12 | 3 x Standard_D4ds_v5 (Ddsv5 family) | > | Confidential ACI | 6 | Confidential container groups | > -> The above covers a single query execution (1 Spark driver + up to 3 -> executors, each using 1 vCPU). Spark pods are provisioned at runtime and +> The above covers a single `small` query execution (1 Spark driver + up to 5 +> executors, with the chart defaults of 1 vCPU each). Spark pods are provisioned at runtime and > removed after query execution completes. Multiple queries can run -> concurrently — add 4 vCPUs of Confidential ACI quota per additional concurrent query. +> concurrently - allow up to 6 vCPUs of Confidential ACI quota per additional +> concurrent `small` query with those defaults. Larger scale SKUs or deployment +> overrides require more quota; see [Scale SKU configuration](#scale-sku-configuration). +> If you change the AKS SKU or node count below, recalculate the corresponding +> VM-family and regional vCPU quota and leave headroom for upgrades. > The `managedcleanroom` CLI extension is **not required** for this guide. +The examples below target the **production RP and frontend** in `westus`, with +collaboration resources in `westus`. Choose a supported resource region where your +subscription has sufficient quota. ARM requests use `2026-09-30-preview`; +the frontend API version is separate and remains `2026-03-01-preview`. + ### 1.2 Terminal T1 (Owner) — Variables ```powershell +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true az login $account = az account show -o json | ConvertFrom-Json $subscription = $account.id @@ -132,6 +145,8 @@ $tenantId = $account.tenantId $rpLocation = "westus" $resourceLocation = "westus" # Location where AKS, Container Groups, and all required resources are created +$aksSku = "Standard_D4ds_v5" +$nodePoolSize = 3 # Supported resourceLocation values: # centralindia, eastasia, eastus, eastus2, germanywestcentral, italynorth, # japaneast, northeurope, southcentralus, southeastasia, switzerlandnorth, @@ -141,7 +156,7 @@ $collabRg = "" # ARM API $armEndpoint = "https://management.azure.com" -$armApiVersion = "2026-04-30-preview" +$armApiVersion = "2026-09-30-preview" $collabArmUrl = "$armEndpoint/subscriptions/$subscription/resourceGroups/$collabRg/providers/Microsoft.CleanRoom/Collaborations/$collabName" ``` @@ -157,6 +172,8 @@ az provider register --namespace Microsoft.ContainerService ### 1.4 Each Collaborator Terminal — Variables ```powershell +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true az login $account = az account show -o json | ConvertFrom-Json $subscription = $account.id @@ -172,7 +189,7 @@ $personaEmail = "" az group create --name $personaRg --location $location -o none 2>$null -$frontend = "https://prod.workload-frontendwestus.cleanroom.cloudapp.azure.net" +$frontend = "https://prod-nonattested.workload-frontendwestus.cleanroom.cloudapp.azure.net" $feApiVersion = "2026-03-01-preview" $oidcStorageUrl = "https://cleanroomoidc.z22.web.core.windows.net" # Required for tenants where Federated Identity Credentials with MI are blocked by policy; specify a whitelisted pre-provisioned storage account name. For other tenants, leave blank ("") and a new storage account will be provisioned by the scripts. @@ -184,7 +201,7 @@ function Invoke-Frontend { $url = if ($Path) { "$frontend/collaborations/$Path" } else { "$frontend/collaborations" } if ($url -notmatch '\?') { $url += "?api-version=$feApiVersion" } else { $url += "&api-version=$feApiVersion" } - $params = @{ Uri = $url; Method = $Method; Headers = $headers; SkipCertificateCheck = $true } + $params = @{ Uri = $url; Method = $Method; Headers = $headers } if ($Body) { $params.Body = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 20 } $params.ContentType = "application/json" @@ -193,6 +210,13 @@ function Invoke-Frontend { } ``` +> The `-nonattested` frontend uses standard, CA-issued TLS. Keep certificate +> verification enabled. TLS terminates outside the TEE at this endpoint, so it +> does not provide the attestation guarantee of the primary frontend endpoint. +> If you want TLS termination inside the TEE, set `$frontend` to the original +> production frontend endpoint: +> `https://prod.workload-frontendwestus.cleanroom.cloudapp.azure.net`. + ### 1.5 Acquire Token & Extract OID `[EACH COLLABORATOR]` #### 1.5.1 Acquire Token @@ -232,6 +256,8 @@ Write-Host "JWT oid: $personaOid" ## Step 02: Create Collaboration `[OWNER]` +> **Terminal: T1 (Owner)** + ### 2.1 Create Resource Group ```powershell @@ -247,6 +273,10 @@ $createBody = @{ properties = @{ collaborators = @(@{ userIdentifier = $collaboratorEmail }) resourceLocation = $resourceLocation + targetResourceConfiguration = @{ + aksSku = $aksSku + nodePoolSize = $nodePoolSize + } } } | ConvertTo-Json -Depth 5 [System.IO.File]::WriteAllText("$PWD/body.json", $createBody) @@ -263,6 +293,44 @@ az rest --method PUT ` > **NOTE**: `location` is the ARM RP location (`$rpLocation`). `resourceLocation` controls where > actual resources (AKS cluster, CACI instances) are deployed — set via `$resourceLocation`. +The `properties.targetResourceConfiguration` object controls the AKS node pool +at creation time: + +| Property | Supported values | Default | +|---|---|---| +| `aksSku` | `Standard_D4ds_v5`, `Standard_D8ds_v5`, `Standard_D16ds_v5`, `Standard_D32ds_v5` | `Standard_D4ds_v5` | +| `nodePoolSize` | Integer from `3` through `10` | `3` | + +Both `aksSku` and `nodePoolSize` are optional. When omitted, they default to +`Standard_D4ds_v5` and `3`, respectively. These are creation-time settings, not +collaboration-update arguments. + +#### Optional public IP tagging + +The same target configuration can also accept `iPTagConfiguration`, with both +`type` and `value`, to tag public IP resources created for the collaboration. +These are networking IP tags, not ordinary ARM resource tags. + +| Type | Example value | Intended use | +|---|---|---| +| `FirstPartyUsage` | `/AzureCleanRoomsProd` | Approved Microsoft first-party production usage | +| `FirstPartyUsage` | `/AzureCleanRoomsNonProd` | Approved Microsoft first-party non-production usage | + +Use only IP-tag values approved for your subscription and scenario. To create a +collaboration with IP tags, use the following value for +`properties.targetResourceConfiguration` in the creation body: + +```json +{ + "iPTagConfiguration": { + "type": "FirstPartyUsage", + "value": "/AzureCleanRoomsProd" + } +} +``` + +The JSON property name `iPTagConfiguration` is case-sensitive. + **Runtime**: ~25 minutes. Poll `provisioningState` until `Succeeded`: ```powershell @@ -366,6 +434,13 @@ if ($invitations) { } ``` +List the active frontend collaborators: + +```powershell +(Invoke-Frontend -Path "$collabId/collaborators" -Method GET).collaborators | + Format-Table +``` + --- ## Step 04: Provision Resources & Upload Data `[EACH COLLABORATOR]` @@ -400,6 +475,9 @@ $queryName = "query1$suffix" Write-Host "Iteration: $iteration | Suffix: '$suffix' | Query: '$queryName'" ``` +Use a distinct suffix for each dataset iteration. The scripts preserve +datastore metadata by suffix so earlier outputs can still be downloaded. + ### 4.4 Upload Data ```powershell @@ -460,7 +538,7 @@ Invoke-Frontend -Path "$collabId/oidc/setIssuerUrl" -Method POST ` ``` > **CRITICAL**: `contractId` must be `"Analytics"` (capital A). `-userId` must be -> the JWT `oid` from Step 01.4. +> the JWT `oid` from Step 1.5.2. **Verify**: ```powershell @@ -481,7 +559,7 @@ az identity federated-credential list ` ```powershell if ($persona -eq "woodgrove") { - # Scope Woodgrove's input dataset to a sub folder inside its container + # Scope Woodgrove's input dataset to a subfolder inside its container. ./scripts/08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona ` -subdirectory "2025-09-01" } else { @@ -494,7 +572,8 @@ if ($persona -eq "woodgrove") { > The Woodgrove branch above passes `-subdirectory "2025-09-01"` so its input > dataset is scoped to a single date folder inside the container. Northwind's > input dataset is left at the container root and sees all four days produced -> by `generate-data.ps1`. For the full parameter reference, see +> by `generate-data.ps1`. Omit `-subdirectory` to use the entire container. +> For the full parameter reference, see > [Optional dataset parameters](#optional-dataset-parameters) in Appendix D. > **Bring your own data**: If you want to provide your own datasets, upload your data directly to the @@ -640,8 +719,16 @@ Write-Host "Query state: $state" ## Step 09: Execute Query `[WOODGROVE]` +Set `scaleSku` in the run request to `small`, `medium`, or `large`. The service +defaults to `small` when omitted. This query setting is separate from the AKS +VM SKU and node count selected when creating the collaboration. + ```powershell -$runBody = @{ runId = [guid]::NewGuid().ToString() } +$scaleSku = "small" +$runBody = @{ + runId = [guid]::NewGuid().ToString() + scaleSku = $scaleSku +} $runResult = Invoke-Frontend -Path "$collabId/analytics/queries/$queryName/run" ` -Method POST -Body $runBody @@ -651,18 +738,53 @@ Write-Host "Job ID: $jobId" > `"status": "success"` means accepted for scheduling, not completed. Takes 10-20 min. +### Scale SKU configuration + +The current Spark frontend profiles map the run's `scaleSku` as follows: + +| `scaleSku` | Driver memory | Memory per executor | Maximum executors | +|---|---|---|---| +| `small` (default) | `4g` | `8g` | 5 | +| `medium` | `8g` | `16g` | 10 | +| `large` | `12g` | `24g` | 20 | + +Memory values use Spark's notation. Driver cores, executor cores, and minimum +executors are inherited from the deployment configuration, not set by these +profiles. The chart defaults are **1 driver core, 1 core per executor, and +1 minimum executor**; deployments can override them. Maximum executors is a +scaling limit, not a fixed count. Account for memory overhead and available +regional capacity in addition to CPU quota. + +To inspect the effective settings without executing the query, send +`dryRun: true` in the same request body and inspect `skuSettings` in the response. +Omit `dryRun` (or set it to `false`) for actual execution. + > **Network connectivity**: This step requires the ACCR Frontend Service to reach the Analytics Endpoint of the Collaboration. It can time out due to tenant-specific network configurations: > > 1. **NSG (Network Security Group)**: If your tenant has NSGs blocking inbound internet access to the AKS Analytics endpoint on port 443, the query will fail. Contact the ACCR team with the `tenantId` of the collaboration so we can whitelist your tenant — an NSG rule will be updated to allow port 443 access to the AKS cluster. > 2. **[AVNM (Azure Virtual Network Manager)](https://learn.microsoft.com/en-us/azure/virtual-network-manager/)**: This is a tenant-level policy. Your tenant admin needs to create an AVNM rule to allow port 443 access from the internet by following the documentation linked above. +**Optional: cancel a run.** After submitting a query, use the following request +only if you want to cancel it before completion: + +```powershell +Invoke-Frontend -Path "$collabId/analytics/queries/$queryName/runs/$jobId/cancel" ` + -Method POST +``` + > **Date-range filtering**: To read datasets within a specific date range, -> pass `startDate` and `endDate` in the request body: +> include `startDate` and `endDate` alongside `scaleSku` in the request body: > > ```powershell -> $runBody = @{ runId = [guid]::NewGuid().ToString(); startDate = "2025-09-01"; endDate = "2025-09-02" } +> $runBody = @{ +> runId = [guid]::NewGuid().ToString() +> scaleSku = $scaleSku +> startDate = "2025-09-01" +> endDate = "2025-09-02" +> } > $runResult = Invoke-Frontend -Path "$collabId/analytics/queries/$queryName/run" ` > -Method POST -Body $runBody +> $jobId = $runResult.id > ``` --- @@ -727,14 +849,19 @@ $audit | ConvertTo-Json -Depth 10 ### 11.3 Download Output -Auto-detects SSE/CPK mode from metadata. Pass `-JobId` to filter to a specific run. +Auto-detects SSE/CPK mode from suffix-specific output metadata and uses its +container and, for CPK, local DEK file. In both modes, `-JobId` selects the exact +run directory under `Analytics///` and downloads all its CSV +partitions. Blob paths are preserved under the output directory. ```powershell ./scripts/11-download-output.ps1 -resourceGroup $personaRg ` - -datasetSuffix "$suffix" -JobId $jobId + -datasetSuffix "$suffix" -JobId $jobId ` + -OutputDir "./generated/output/$EncryptionMode-$jobId" ``` -> Output CSVs are saved to `generated/output/`. Without `-JobId`, downloads the latest. +> Use a distinct `-OutputDir` for each run. Without `-JobId`, the +> script downloads all matching CSV outputs in the selected container. --- @@ -748,7 +875,7 @@ Auto-detects SSE/CPK mode from metadata. Pass `-JobId` to filter to a specific r ```powershell $kc = az rest --method POST ` --url "$collabArmUrl/getReadonlyKubeConfig`?api-version=$armApiVersion" ` - --resource $armResource -o json | ConvertFrom-Json + --resource $armEndpoint -o json | ConvertFrom-Json $bytes = [Convert]::FromBase64String($kc.kubeconfig) [System.Text.Encoding]::UTF8.GetString($bytes) | @@ -757,7 +884,8 @@ $bytes = [Convert]::FromBase64String($kc.kubeconfig) ### 12.2 Open Grafana Dashboard -Retrieves admin credentials, opens the browser, and port-forwards to Grafana. +Uses the read-only kubeconfig to access diagnostics through Grafana, prints the +URL to open manually in your browser, and port-forwards until you press Ctrl+C. ```powershell ./scripts/12-open-grafana-dashboard.ps1 -KubeConfigPath "./readonly.kubeconfig" @@ -770,7 +898,7 @@ Login with `admin` and the password printed by the script. ## Appendix A: Federated Credential Subject Reference Format: `{contractId}-{ownerId}` where `contractId` = `"Analytics"` (capital A) -and `ownerId` = JWT `oid` from Step 01.4. +and `ownerId` = JWT `oid` from Step 1.5.2. MSA accounts: JWT `oid` ≠ `az ad signed-in-user show --query id`. Always use JWT `oid`. @@ -792,8 +920,8 @@ az identity federated-credential create --name "Analytics-$personaOid-federation | Error | Cause | Fix | |---|---|---| | `SPARK_JOB_FAILED: ExitCode 1` | Federated credential subject mismatch | See [Appendix A](#appendix-a-federated-credential-subject-reference) | -| `AADSTS700211: No matching federated identity record` | Wrong issuer URL or stale FIC | Republish dataset; delete/recreate FIC | -| `SSL certificate verify failed` | Endpoint cert mismatch | Use `-SkipCertificateCheck` on `Invoke-RestMethod` | +| `AADSTS700211: No matching federated identity record` | Wrong issuer URL in dataset or stale FIC | Republish dataset; delete/recreate FIC | +| `SSL certificate verify failed` | Wrong frontend endpoint | Verify `$frontend` points to the non-attested endpoint; do not disable TLS verification | | `404 Not Found` on frontend | Using ARM resource ID instead of frontend UUID | Use UUID from `Invoke-Frontend -Path ""` | | `ContractNotFound` | Stale CCF endpoint | Create new collaboration | | `Already voted / Conflict` | Publisher already voted | Check query state; skip an accept vote if already Accepted. Do not ignore other conflicts | @@ -837,7 +965,7 @@ Supported formats: `csv`, `parquet`, `json`. | Parameter | Description | |---|---| -| `subdirectory` | Prefix inside the dataset's container to scope the dataset to a sub folder(e.g. `2025-09-01`). Optional, defaults to `""` (entire container). Pass it via the `-subdirectory` parameter of `scripts/08-build-dataset-body.ps1` — see [Step 6.1](#61-build-dataset-body-json) for the call site. | +| `subdirectory` | Prefix inside the dataset's container to scope the dataset to a subfolder (e.g. `2025-09-01`). Optional, defaults to `""` (entire container). Pass it via the `-subdirectory` parameter of `scripts/08-build-dataset-body.ps1` - see [Step 6.1](#61-build-dataset-body-json). | --- @@ -854,7 +982,7 @@ Supported formats: `csv`, `parquet`, `json`. - **Pre-conditions** enforce a minimum row count per view. If any view has fewer rows than `minRowCount`, the query aborts. - **Post-filters** remove groups from the output whose aggregation count is below a threshold, preventing identification of individuals. -Both are defined in the query segments. Edit the thresholds before publishing the query (Step 08). +Both are defined in the query segments. Edit the thresholds before publishing the query (Step 07). --- @@ -863,7 +991,7 @@ Both are defined in the query segments. Edit the thresholds before publishing th ### ARM API (via `az rest`) Base: `https://management.azure.com` -API version: `2026-04-30-preview` +API version: `2026-09-30-preview` | Operation | Method | URL | |---|---|---| @@ -883,6 +1011,7 @@ API version: `2026-03-01-preview` | List collaborations | GET | `/` | | List invitations | GET | `/{id}/invitations` | | Accept invitation | POST | `/{id}/invitations/{invId}/accept` | +| List collaborators | GET | `/{id}/collaborators` | | OIDC keys | GET | `/{id}/oidc/keys` | | Set issuer URL | POST | `/{id}/oidc/setIssuerUrl` | | Publish dataset | POST | `/{id}/analytics/datasets/{docId}/publish` | @@ -894,6 +1023,7 @@ API version: `2026-03-01-preview` | Run query | POST | `/{id}/analytics/queries/{docId}/run` | | Run result | GET | `/{id}/analytics/runs/{jobId}` | | Run history | GET | `/{id}/analytics/queries/{docId}/runs` | +| Cancel run | POST | `/{id}/analytics/queries/{docId}/runs/{runId}/cancel` | | Audit events | GET | `/{id}/analytics/auditevents` | --- @@ -948,20 +1078,33 @@ For CI/CD automation, service principals can replace interactive user login. # Use get-sp-token-sni.ps1 for MSAL SNI (x5c) auth $token = ./scripts/common/get-sp-token-sni.ps1 ` -appId "" -tenantId "" -certPemPath "" +$personaTokenFile = Join-Path ([System.IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt" +$token | Out-File -FilePath $personaTokenFile -NoNewline $env:CLEANROOM_FRONTEND_TOKEN = $token ``` +Use this instead of interactive token acquisition in Step 1.5.1, then extract +the token's `oid` as shown in Step 1.5.2. + ### Add SPN as Collaborator ```powershell -az managedcleanroom collaboration add-collaborator ` - --collaboration-name --resource-group ` - --user-identifier ` - --object-id ` - --tenant-id +$addBody = @{ + collaborator = @{ + userIdentifier = "" + objectId = "" + tenantId = "" + } +} | ConvertTo-Json -Depth 3 +[System.IO.File]::WriteAllText("$PWD/body.json", $addBody) +az rest --method POST ` + --url "$collabArmUrl/addCollaborator`?api-version=$armApiVersion" ` + --resource $armEndpoint ` + --headers "Content-Type=application/json" ` + --body "@body.json" ``` -> **Note**: `--object-id` must be from the **Enterprise Application** (service principal), not the app registration. SPNs auto-activate — no invitation acceptance needed. +> **Note**: `objectId` must be from the **Enterprise Application** (service principal), not the app registration. SPNs auto-activate — no invitation acceptance needed. ### Federated Credential Subject @@ -977,5 +1120,5 @@ Analytics-{spObjectId} |---|---| | `AADSTS700027: certificate not registered` | Use Python MSAL with `public_certificate`, not `az login` | | `Credential lifetime exceeds max value` | Use OneCert + `trustedCertificateSubjects` | -| `InvalidCollaboratorIdentifier` | Add `--object-id` and `--tenant-id` to `add-collaborator` | +| `InvalidCollaboratorIdentifier` | Add `objectId` and `tenantId` to the `collaborator` object in the `addCollaborator` request | | `is_schema_compatible: Missing field` | Output `allowedFields` must include all query output columns | diff --git a/demos/analytics-using-managedcleanroom/README-CLI.md b/demos/analytics-using-managedcleanroom/README-CLI.md index ebe57a8..a91d5f5 100644 --- a/demos/analytics-using-managedcleanroom/README-CLI.md +++ b/demos/analytics-using-managedcleanroom/README-CLI.md @@ -62,17 +62,24 @@ providing your own data and query. - [Overview](#overview) - [Step 01: Prerequisites](#step-01-prerequisites) `[ALL]` - [1.1 Requirements](#11-requirements) + - [IMPORTANT: Capacity planning for query execution](#important-capacity-planning-for-query-execution) - [1.2 Terminal T1 (Owner) — Variables](#12-terminal-t1-owner--variables) - [1.3 One-Time Owner Setup](#13-one-time-owner-setup) - [1.4 Each Collaborator Terminal — Variables](#14-each-collaborator-terminal--variables) - [1.5 Acquire Token, Extract OID & Configure CLI](#15-acquire-token-extract-oid--configure-cli-each-collaborator) `[EACH COLLABORATOR]` - [Step 02: Create Collaboration](#step-02-create-collaboration) `[OWNER]` - - [2.1 Create Collaboration & Enable Workload](#21-create-collaboration--enable-workload) - - [2.2 Add More Collaborators (Optional)](#22-add-more-collaborators-optional) + - [2.1 Create Resource Group](#21-create-resource-group) + - [2.2 Create Collaboration](#22-create-collaboration) + - [2.3 Enable Analytics Workload](#23-enable-analytics-workload) + - [2.4 Add More Collaborators (Optional)](#24-add-more-collaborators-optional) - [Step 03: Accept Invitations](#step-03-accept-invitations) `[EACH COLLABORATOR]` - [Step 04: Provision Resources & Upload Data](#step-04-provision-resources--upload-data) `[EACH COLLABORATOR]` - [Step 05: OIDC Identity & Access](#step-05-oidc-identity--access) `[EACH COLLABORATOR]` - [Step 06: Publish Datasets](#step-06-publish-datasets) `[EACH COLLABORATOR]` + - [6.1 Build Dataset Body JSON](#61-build-dataset-body-json) + - [6.2 Publish Input Dataset](#62-publish-input-dataset) + - [6.3 Publish Output Dataset (Woodgrove only)](#63-publish-output-dataset-woodgrove-only) + - [6.4 Prepare CPK Keys (CPK mode only)](#64-prepare-cpk-keys-cpk-mode-only) - [Step 07: Publish Query](#step-07-publish-query) `[WOODGROVE]` - [Step 08: Approve Query](#step-08-approve-query) `[EACH COLLABORATOR]` - [Step 09: Execute Query](#step-09-execute-query) `[WOODGROVE]` @@ -96,29 +103,76 @@ providing your own data and query. | Requirement | Details | |---|---| | Azure CLI | 2.75.0+ | -| `managedcleanroom` extension | `az extension add --name managedcleanroom --version 1.0.0b6` | +| `managedcleanroom` extension | `az extension add --name managedcleanroom --version 1.0.0b9 --upgrade` | | PowerShell | 7.x+ | | MSAL.PS module | `Install-Module MSAL.PS -Scope CurrentUser -Force` | | azcopy | v10+ (CPK mode only) | | kubectl | Latest stable | -> **Quota check:** This sample deploys an AKS cluster and Confidential ACI -> container groups in the `$resourceLocation` region (**West US** by default). Ensure your subscription has the -> following minimum quota in that region before proceeding: -> -> | Resource | Minimum vCPUs | SKU / Family | -> |---|---|---| -> | AKS node pool | 8 | Standard_D4ds_v5 (Ddsv5 family) | -> | Confidential ACI | 6 | Confidential container groups | -> -> The above covers a single query execution (1 Spark driver + up to 3 -> executors, each using 1 vCPU). Spark pods are provisioned at runtime and -> removed after query execution completes. Multiple queries can run -> concurrently — add 4 vCPUs of Confidential ACI quota per additional concurrent query. +#### IMPORTANT: Capacity planning for query execution + +Complete capacity planning in `$resourceLocation` before creating the +collaboration. The AKS SKU and node-pool size are creation-time settings and +cannot be updated later. + +**1. Select a query scale SKU based on input data size.** + +| Input data processed by the query | `scaleSku` | +|---|---| +| Less than 300 GB | `small` | +| 300–600 GB | `medium` | +| More than 600 GB | `large` | + +> **Preview:** `large` is not ready for production use. Validate it with your +> workload before relying on it. + +**2. Decide the required maximum parallel queries and select the collaboration +configuration.** + +The service derives the internal scheduling capacity from `$aksSku` and +`$nodePoolSize`. Customers must configure both values on the collaboration at +creation time and ensure the required Ddsv5 quota is available in the +subscription in `$resourceLocation`. Select a configuration whose maximum +parallel queries meets your requirement for the `scaleSku` chosen in step 1: + +| `aksSku` | `nodePoolSize` | Max `small` queries | Max `medium` queries | Max `large` queries | Required Ddsv5 quota | +|---|---:|---:|---:|---:|---:| +| `Standard_D4ds_v5` | 3 | 10 | 5 | 3 | 12 vCPUs | +| `Standard_D4ds_v5` | 4 | 15 | 8 | 5 | 16 vCPUs | +| `Standard_D8ds_v5` | 3 | 20 | 10 | 6 | 24 vCPUs | + +\* Higher configurations are possible but are not yet validated or supported. + +**3. Calculate the Confidential ACI quota required for query execution.** + +Let `N` be the maximum number of parallel queries you plan to run. Ensure the +subscription has the following Confidential ACI quota in `$resourceLocation`: + +| `scaleSku` | Pods per query | Confidential vCPUs per query | Required Confidential vCPU quota | Required Confidential Container Groups quota | +|---|---:|---:|---:|---:| +| `small` | 6 | 34 | `34 × N` | `6 × N` | +| `medium` | 11 | 64 | `64 × N` | `11 × N` | +| `large` | 21 | 124 | `124 × N` | `21 × N` | + +Actual runnable parallelism is the lower of the collaboration capacity above and +the available Confidential ACI quota. Leave headroom for retries, +terminating pods, other subscription workloads, and regional Confidential ACI +availability; these values are planning ceilings, not throughput guarantees. + +> [!NOTE] +> Upcoming scheduler updates will raise query scheduling density. + +The examples below target the **production RP and frontend** in `westus`, with +collaboration resources in `westus`. Choose a supported resource region where your +subscription has sufficient quota. Extension `1.0.0b9` uses +`2026-09-30-preview` for collaboration creation; the frontend API version is +separate and remains `2026-03-01-preview`. ### 1.2 Terminal T1 (Owner) — Variables ```powershell +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true az login $account = az account show -o json | ConvertFrom-Json $subscription = $account.id @@ -126,6 +180,8 @@ $tenantId = $account.tenantId $rpLocation = "westus" $resourceLocation = "westus" # Location where AKS, Container Groups, and all required resources are created +$aksSku = "Standard_D4ds_v5" +$nodePoolSize = 3 # Supported resourceLocation values: # centralindia, eastasia, eastus, eastus2, germanywestcentral, italynorth, # japaneast, northeurope, southcentralus, southeastasia, switzerlandnorth, @@ -146,6 +202,8 @@ az provider register --namespace Microsoft.ContainerService ### 1.4 Each Collaborator Terminal — Variables ```powershell +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true az login $account = az account show -o json | ConvertFrom-Json $subscription = $account.id @@ -161,10 +219,17 @@ $personaEmail = "" az group create --name $personaRg --location $location -o none 2>$null -$frontend = "https://prod.workload-frontendwestus.cleanroom.cloudapp.azure.net" +$frontend = "https://prod-nonattested.workload-frontendwestus.cleanroom.cloudapp.azure.net" $oidcStorageUrl = "https://cleanroomoidc.z22.web.core.windows.net" # Required for tenants where Federated Identity Credentials with MI are blocked by policy; specify a whitelisted pre-provisioned storage account name. For other tenants, leave blank ("") and a new storage account will be provisioned by the scripts. ``` +> The `-nonattested` frontend uses standard, CA-issued TLS. Keep certificate +> verification enabled. TLS terminates outside the TEE at this endpoint, so it +> does not provide the attestation guarantee of the primary frontend endpoint. +> If you want TLS termination inside the TEE, set `$frontend` to the original +> production frontend endpoint: +> `https://prod.workload-frontendwestus.cleanroom.cloudapp.azure.net`. + ### 1.5 Acquire Token, Extract OID & Configure CLI `[EACH COLLABORATOR]` #### 1.5.1 Acquire Token @@ -204,37 +269,76 @@ Write-Host "JWT oid: $personaOid" ```powershell $env:MANAGEDCLEANROOM_ACCESS_TOKEN = Get-Content $personaTokenFile -Raw -$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1" +$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = $null az managedcleanroom frontend configure --endpoint $frontend ``` +> Run `frontend configure` explicitly when changing environments. Do not rely +> solely on `MANAGEDCLEANROOM_ENDPOINT`: the `1.0.0b9` frontend client reads the +> endpoint from Azure CLI configuration. + --- ## Step 02: Create Collaboration `[OWNER]` > **Terminal: T1 (Owner)** -### 2.1 Create Collaboration & Enable Workload +### 2.1 Create Resource Group ```powershell az group create --name $collabRg --location $rpLocation -o none +``` + +### 2.2 Create Collaboration +```powershell $collaboratorEmail = "" az managedcleanroom collaboration create ` --collaboration-name $collabName ` --resource-group $collabRg ` --location $rpLocation ` --resource-location $resourceLocation ` - --collaborators "[{UserIdentifier:'$collaboratorEmail'}]" ` + --target-resource-configuration "{aks-sku:$aksSku,node-pool-size:$nodePoolSize}" ` + --collaborators "[{user-identifier:'$collaboratorEmail'}]" ` --no-wait ``` > The `--collaborators` flag adds collaborators at creation time itself. -> To add more collaborators later, see [Step 2.2](#22-add-more-collaborators-optional). +> To add more collaborators later, see [Step 2.4](#24-add-more-collaborators-optional). > **NOTE**: `--location` is the ARM RP location (`$rpLocation`). `--resource-location` controls where > actual resources (AKS cluster, CACI instances) are deployed — set via `$resourceLocation`. +The `--target-resource-configuration` argument (alias `--target-config`) controls +the AKS node pool at creation time: + +| Option | Supported values | Default | +|---|---|---| +| `aks-sku` | `Standard_D4ds_v5`, `Standard_D8ds_v5` | `Standard_D4ds_v5` | +| `node-pool-size` | Integer from `3` through `10` | `3` | + +Both `aks-sku` and `node-pool-size` are optional. When omitted, they default to +`Standard_D4ds_v5` and `3`, respectively. These are creation-time settings, not +collaboration-update arguments. + +#### Optional public IP tagging + +The same target configuration can also accept `i-p-tag-configuration`, with both +`type` and `value`, to tag public IP resources created for the collaboration. +These are networking IP tags, not ordinary ARM resource `--tags`. + +| Type | Example value | Intended use | +|---|---|---| +| `FirstPartyUsage` | `/AzureCleanRoomsProd` | Approved Microsoft first-party production usage | +| `FirstPartyUsage` | `/AzureCleanRoomsNonProd` | Approved Microsoft first-party non-production usage | + +Use only IP-tag values approved for your subscription and scenario. Specify IP +tags in `az managedcleanroom collaboration create` with this argument: + +```text + --target-resource-configuration "{i-p-tag-configuration:{type:FirstPartyUsage,value:/AzureCleanRoomsProd}}" ` +``` + **Runtime**: ~25 minutes. Poll `provisioningState` until `Succeeded`: ```powershell @@ -247,6 +351,8 @@ do { } while ($collab.provisioningState -notin @("Succeeded", "Failed")) ``` +### 2.3 Enable Analytics Workload + ```powershell az managedcleanroom collaboration enable-workload ` --collaboration-name $collabName ` @@ -283,9 +389,9 @@ do { } while ($collab.health.healthState -ne "Ok") ``` -### 2.2 Add More Collaborators (Optional) +### 2.4 Add More Collaborators (Optional) -> The owner was already added as a collaborator during `create` (Step 2.1). +> The owner was already added as a collaborator during `create` (Step 2.2). > Use this step to invite additional collaborators (e.g. Northwind in a multi-party scenario). > To add Service Principals (SPNs) instead of user email IDs for automation, see @@ -314,7 +420,6 @@ az managedcleanroom collaboration show ` ```powershell $env:MANAGEDCLEANROOM_ACCESS_TOKEN = Get-Content $personaTokenFile -Raw -$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1" $collabs = (az managedcleanroom frontend collaboration list -o json | ConvertFrom-Json).collaborations $collabs | Format-Table @{L='#';E={[array]::IndexOf($collabs,$_)+1}}, collaborationName, collaborationId, userStatus @@ -341,6 +446,13 @@ if ($invitations) { } ``` +List the active frontend collaborators: + +```powershell +az managedcleanroom frontend collaborator list ` + --collaboration-id $collabId -o table +``` + --- ## Step 04: Provision Resources & Upload Data `[EACH COLLABORATOR]` @@ -375,6 +487,9 @@ $queryName = "query1$suffix" Write-Host "Iteration: $iteration | Suffix: '$suffix' | Query: '$queryName'" ``` +Use a distinct suffix for each dataset iteration. The scripts preserve +datastore metadata by suffix so earlier outputs can still be downloaded. + ### 4.4 Upload Data ```powershell @@ -397,7 +512,6 @@ $variant = if ($EncryptionMode -eq "CPK") { "cpk" } else { "sse" } ```powershell $env:MANAGEDCLEANROOM_ACCESS_TOKEN = Get-Content $personaTokenFile -Raw -$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1" az managedcleanroom frontend configure --endpoint $frontend $jwksDir = "generated/$personaRg" @@ -440,7 +554,7 @@ az managedcleanroom frontend oidc set-issuer-url ` ``` > **CRITICAL**: `contractId` must be `"Analytics"` (capital A). `-userId` must be -> the JWT `oid` from Step 01.4. +> the JWT `oid` from Step 1.5.2. **Verify**: ```powershell @@ -460,9 +574,24 @@ az identity federated-credential list ` ### 6.1 Build Dataset Body JSON ```powershell -./scripts/08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona +if ($persona -eq "woodgrove") { + # Scope Woodgrove's input dataset to a subfolder inside its container. + ./scripts/08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona ` + -subdirectory "2025-09-01" +} else { + # Northwind's input dataset maps to the entire container. + ./scripts/08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona +} ``` +> [!IMPORTANT] +> The Woodgrove branch above passes `-subdirectory "2025-09-01"` so its input +> dataset is scoped to a single date folder inside the container. Northwind's +> input dataset is left at the container root and sees all four days produced +> by `generate-data.ps1`. Omit `-subdirectory` to use the entire container. +> For the full parameter reference, see +> [Optional dataset parameters](#optional-dataset-parameters) in Appendix D. + > **Bring your own data**: If you want to provide your own datasets, upload your data directly to the > storage accounts created for your persona and update `datasetSchema` and `datasetAccessPolicy` in the dataset > body files: `generated/publish/$persona-input-dataset.json` and `generated/publish/$persona-output-dataset.json`. @@ -619,29 +748,88 @@ az managedcleanroom frontend analytics query show ` ## Step 09: Execute Query `[WOODGROVE]` +Set `scaleSku` in the run request to `small`, `medium`, or `large`. The service +defaults to `small` when omitted. This query setting is separate from the AKS +VM SKU and node count selected when creating the collaboration. + +Extension `1.0.0b9` does not expose a `--scale-sku` flag. Use a JSON request body: + ```powershell +$scaleSku = "small" +$runBody = @{ scaleSku = $scaleSku } +[System.IO.File]::WriteAllText("$PWD/generated/run-config.json", ($runBody | ConvertTo-Json)) + $runResult = az managedcleanroom frontend analytics query run ` --collaboration-id $collabId ` - --document-id $queryName -o json | ConvertFrom-Json + --document-id $queryName ` + --body "@generated/run-config.json" -o json | ConvertFrom-Json $jobId = $runResult.id Write-Host "Job ID: $jobId" ``` +Do not combine `--body` with `--start-date`, `--end-date`, `--dry-run`, or +`--use-optimizer`; include any of these settings in the JSON body instead. + > The CLI auto-generates a run ID. Each invocation starts a new execution. +> `"status": "success"` means accepted for scheduling, not completed. Takes 10-20 min. + +### Scale SKU configuration + +The current Spark frontend profiles map the run's `scaleSku` as follows: + +| `scaleSku` | Driver memory | Memory per executor | Maximum executors | Input data guidance | +|---|---|---|---:|---| +| `small` (default) | `4g` | `8g` | 5 | Less than 300 GB | +| `medium` | `8g` | `16g` | 10 | 300–600 GB | +| `large` (preview) | `12g` | `24g` | 20 | More than 600 GB | + +`large` is not ready for production use. See +[IMPORTANT: Capacity planning for query execution](#important-capacity-planning-for-query-execution) +before choosing a scale SKU or collaboration size. + +Memory values use Spark's notation. Driver cores, executor cores, and minimum +executors are inherited from the deployment configuration, not set by these +profiles. The chart defaults are **1 driver core, 1 core per executor, and +1 minimum executor**; deployments can override them. Maximum executors is a +scaling limit, not a fixed count. Spark container cores do not represent the +Confidential ACI group quota used in the capacity calculation above. Account for +memory overhead and available regional capacity in addition to CPU quota. + +To inspect the effective settings without executing the query, send +`dryRun: true` in the same request body and inspect `skuSettings` in the response. +Omit `dryRun` (or set it to `false`) for actual execution. > **Network connectivity**: This step requires the ACCR Frontend Service to reach the Analytics Endpoint of the Collaboration. It can time out due to tenant-specific network configurations: > > 1. **NSG (Network Security Group)**: If your tenant has NSGs blocking inbound internet access to the AKS Analytics endpoint on port 443, the query will fail. Contact the ACCR team with the `tenantId` of the collaboration so we can whitelist your tenant — an NSG rule will be updated to allow port 443 access to the AKS cluster. > 2. **[AVNM (Azure Virtual Network Manager)](https://learn.microsoft.com/en-us/azure/virtual-network-manager/)**: This is a tenant-level policy. Your tenant admin needs to create an AVNM rule to allow port 443 access from the internet by following the documentation linked above. +**Optional: cancel a run.** After submitting a query, use the following command +only if you want to cancel it before completion: + +```powershell +az managedcleanroom frontend analytics query cancel-run ` + --collaboration-id $collabId ` + --document-id $queryName ` + --run-id $jobId +``` + > **Date-range filtering**: To read datasets within a specific date range, -> add `--start-date` and `--end-date`: +> include `startDate` and `endDate` alongside `scaleSku` in the request body: > > ```powershell +> $runBody = @{ +> scaleSku = $scaleSku +> startDate = "2025-09-01" +> endDate = "2025-09-02" +> } +> [System.IO.File]::WriteAllText("$PWD/generated/run-config.json", ($runBody | ConvertTo-Json)) > $runResult = az managedcleanroom frontend analytics query run ` > --collaboration-id $collabId ` -> --document-id $queryName --start-date "2025-09-01" --end-date "2025-09-02" -o json | ConvertFrom-Json +> --document-id $queryName ` +> --body "@generated/run-config.json" -o json | ConvertFrom-Json +> $jobId = $runResult.id > ``` --- @@ -710,14 +898,19 @@ az managedcleanroom frontend analytics auditevent list ` ### 11.3 Download Output -Auto-detects SSE/CPK mode from metadata. Pass `-JobId` to filter to a specific run. +Auto-detects SSE/CPK mode from suffix-specific output metadata and uses its +container and, for CPK, local DEK file. In both modes, `-JobId` selects the exact +run directory under `Analytics///` and downloads all its CSV +partitions. Blob paths are preserved under the output directory. ```powershell ./scripts/11-download-output.ps1 -resourceGroup $personaRg ` - -datasetSuffix "$suffix" -JobId $jobId + -datasetSuffix "$suffix" -JobId $jobId ` + -OutputDir "./generated/output/$EncryptionMode-$jobId" ``` -> Output CSVs are saved to `generated/output/`. Without `-JobId`, downloads the latest. +> Use a distinct `-OutputDir` for each run. Without `-JobId`, the +> script downloads all matching CSV outputs in the selected container. --- @@ -740,7 +933,8 @@ $bytes = [Convert]::FromBase64String($kc.kubeconfig) ### 12.2 Open Grafana Dashboard -Retrieves admin credentials, opens the browser, and port-forwards to Grafana. +Uses the read-only kubeconfig to access diagnostics through Grafana, prints the +URL to open manually in your browser, and port-forwards until you press Ctrl+C. ```powershell ./scripts/12-open-grafana-dashboard.ps1 -KubeConfigPath "./readonly.kubeconfig" @@ -753,7 +947,7 @@ Login with `admin` and the password printed by the script. ## Appendix A: Federated Credential Subject Reference Format: `{contractId}-{ownerId}` where `contractId` = `"Analytics"` (capital A) -and `ownerId` = JWT `oid` from Step 01.4. +and `ownerId` = JWT `oid` from Step 1.5.2. MSA accounts: JWT `oid` ≠ `az ad signed-in-user show --query id`. Always use JWT `oid`. @@ -776,10 +970,10 @@ az identity federated-credential create --name "Analytics-$personaOid-federation |---|---|---| | `SPARK_JOB_FAILED: ExitCode 1` | Federated credential subject mismatch | See [Appendix A](#appendix-a-federated-credential-subject-reference) | | `AADSTS700211: No matching federated identity record` | Wrong issuer URL in dataset or stale FIC | Republish dataset; delete/recreate FIC | -| `SSL certificate verify failed` | Endpoint cert mismatch | Set `$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1"` | +| `SSL certificate verify failed` | Wrong frontend endpoint or stale endpoint configuration | Re-run `az managedcleanroom frontend configure --endpoint $frontend`; do not disable TLS verification | | `404 Not Found` on frontend | Using ARM ID instead of frontend UUID | Use UUID from `frontend collaboration list` | | `ContractNotFound` | Stale CCF endpoint | Create new collaboration | -| `Python 3.13 tuple error` | CLI extension bug | Upgrade to v1.0.0b6+ | +| `Python 3.13 tuple error` | CLI extension bug | Upgrade to `managedcleanroom` extension `1.0.0b9` | | `Already voted / Conflict` | Publisher already voted | Check query state; skip an accept vote if already Accepted. Do not ignore other conflicts | | `PENDING_RERUN` | Normal scheduling | Keep polling | @@ -817,6 +1011,12 @@ Runtime: SKR release → KEK private → unwrap DEK → CPK header → Storage Fields not in `allowedFields` are excluded from query access — prevents PII exposure. Supported formats: `csv`, `parquet`, `json`. +### Optional dataset parameters + +| Parameter | Description | +|---|---| +| `subdirectory` | Prefix inside the dataset's container to scope the dataset to a subfolder (e.g. `2025-09-01`). Optional, defaults to `""` (entire container). Pass it via the `-subdirectory` parameter of `scripts/08-build-dataset-body.ps1` - see [Step 6.1](#61-build-dataset-body-json). | + --- ## Appendix E: Query Structure Reference @@ -832,7 +1032,7 @@ Supported formats: `csv`, `parquet`, `json`. - **Pre-conditions** enforce a minimum row count per view. If any view has fewer rows than `minRowCount`, the query aborts. - **Post-filters** remove groups from the output whose aggregation count is below a threshold, preventing identification of individuals. -Both are defined in the query segments. Edit the thresholds before publishing the query (Step 08). +Both are defined in the query segments. Edit the thresholds before publishing the query (Step 07). --- @@ -883,17 +1083,24 @@ For CI/CD automation, service principals can replace interactive user login. # Use get-sp-token-sni.ps1 for MSAL SNI (x5c) auth $token = ./scripts/common/get-sp-token-sni.ps1 ` -appId "" -tenantId "" -certPemPath "" +$personaTokenFile = Join-Path ([System.IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt" +$token | Out-File -FilePath $personaTokenFile -NoNewline $env:CLEANROOM_FRONTEND_TOKEN = $token +$env:MANAGEDCLEANROOM_ACCESS_TOKEN = $token +az managedcleanroom frontend configure --endpoint $frontend ``` +Use this instead of interactive token acquisition in Step 1.5.1, then extract +the token's `oid` as shown in Step 1.5.2. + ### Add SPN as Collaborator ```powershell az managedcleanroom collaboration add-collaborator ` - --collaboration-name --resource-group ` - --user-identifier ` - --object-id ` - --tenant-id + --collaboration-name $collabName --resource-group $collabRg ` + --user-identifier "" ` + --object-id "" ` + --tenant-id "" ``` > **Note**: `--object-id` must be from the **Enterprise Application** (service principal), not the app registration. SPNs auto-activate — no invitation acceptance needed. diff --git a/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 b/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 index 596d46f..d7c3be5 100644 --- a/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/05-prepare-data.ps1 @@ -294,7 +294,11 @@ if ($persona -eq "woodgrove") { } $metadataFile = Join-Path $datastoreDir "$persona-datastore-metadata.json" -$datastoreMetadata | ConvertTo-Json -Depth 10 | Out-File -FilePath $metadataFile -Encoding utf8 +$versionedMetadataFile = Join-Path $datastoreDir "$persona-datastore-metadata$datasetSuffix.json" +$metadataJson = $datastoreMetadata | ConvertTo-Json -Depth 10 +$metadataJson | Out-File -FilePath $metadataFile -Encoding utf8 +$metadataJson | Out-File -FilePath $versionedMetadataFile -Encoding utf8 Write-Host "Datastore metadata saved to: $metadataFile" -ForegroundColor Yellow +Write-Host "Versioned datastore metadata saved to: $versionedMetadataFile" -ForegroundColor Yellow Write-Host "`nData preparation complete for '$persona' ($variant mode)." -ForegroundColor Green diff --git a/demos/analytics-using-managedcleanroom/scripts/08-build-dataset-body.ps1 b/demos/analytics-using-managedcleanroom/scripts/08-build-dataset-body.ps1 index 0942352..ea7de59 100644 --- a/demos/analytics-using-managedcleanroom/scripts/08-build-dataset-body.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/08-build-dataset-body.ps1 @@ -16,7 +16,8 @@ Prerequisites: - 05-prepare-data.ps1 (generates datastore metadata) - 06-setup-oidc-storage.ps1 (generates identity metadata + issuer URL) - - 08-prepare-dataset-keys.ps1 (CPK only — generates KEKs, updates metadata) + For CPK, publish these dataset bodies before running 08-prepare-dataset-keys.ps1; + key preparation needs the SKR policy of the published dataset. #> param( [Parameter(Mandatory)] diff --git a/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 b/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 index 66b7209..9dd2f73 100644 --- a/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/08-prepare-dataset-keys.ps1 @@ -10,8 +10,8 @@ 4. Wraps the DEK with the KEK (RSA-OAEP-SHA256, client-side). 5. Stores the wrapped DEK as a Key Vault secret. - This script makes frontend calls internally to fetch SKR policies. - The same script works regardless of whether the README uses AZ CLI or REST API. + This script uses HTTPS REST calls to fetch SKR policies; the managedcleanroom + CLI extension is not required and its configuration is not changed. Prerequisites: - 04-prepare-resources.ps1 must have been run. @@ -36,7 +36,8 @@ Output directory. .PARAMETER TokenFile - Token file for frontend authentication. + Token file for frontend authentication. If omitted, uses CLEANROOM_FRONTEND_TOKEN, + then MANAGEDCLEANROOM_ACCESS_TOKEN, then the current Azure CLI ARM access token. #> param( [Parameter(Mandatory)] @@ -99,33 +100,53 @@ if ($feBase.EndsWith('/collaborations')) { $feBase = $feBase.Substring(0, $feBase.Length - '/collaborations'.Length) } -# Try CLI first, fallback to REST function Get-SkrPolicy { param([string]$DatasetName) - # Try az CLI - $env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1" - if ($TokenFile) { - $env:MANAGEDCLEANROOM_ACCESS_TOKEN = (Get-Content $TokenFile -Raw).Trim() + $endpointUri = $null + if (-not [Uri]::TryCreate($feBase, [UriKind]::Absolute, [ref]$endpointUri) -or + $endpointUri.Scheme -ne "https" -or $endpointUri.Query -or $endpointUri.Fragment -or + $endpointUri.UserInfo) { + throw "frontendEndpoint must be an absolute HTTPS URL without credentials, query, or fragment." } - az managedcleanroom frontend configure --endpoint $feBase 2>&1 | Out-Null - $PSNativeCommandUseErrorActionPreference = $false - $raw = az managedcleanroom frontend analytics skr-policy ` - --collaboration-id $collaborationId ` - --dataset-id $DatasetName 2>&1 - $PSNativeCommandUseErrorActionPreference = $true - - if ($LASTEXITCODE -eq 0) { - $jsonLines = $raw | Where-Object { $_ -is [string] } - return $jsonLines | ConvertFrom-Json + if ($TokenFile) { + if (-not (Test-Path -LiteralPath $TokenFile -PathType Leaf)) { + throw "Frontend token file not found: $TokenFile" + } + $token = ([string](Get-Content -LiteralPath $TokenFile -Raw)).Trim() + } elseif ($env:CLEANROOM_FRONTEND_TOKEN) { + $token = $env:CLEANROOM_FRONTEND_TOKEN.Trim() + } elseif ($env:MANAGEDCLEANROOM_ACCESS_TOKEN) { + $token = $env:MANAGEDCLEANROOM_ACCESS_TOKEN.Trim() + } else { + try { + $token = az account get-access-token --resource "https://management.azure.com/" ` + --query accessToken -o tsv + if ($LASTEXITCODE -ne 0) { throw "Azure CLI exited with code $LASTEXITCODE." } + } catch { + throw "Could not acquire a frontend token. Supply -TokenFile or CLEANROOM_FRONTEND_TOKEN. $($_.Exception.Message)" + } + $token = ($token -join "`n").Trim() + } + if ([string]::IsNullOrWhiteSpace($token)) { + throw "Frontend token is empty. Supply a valid -TokenFile or CLEANROOM_FRONTEND_TOKEN." } - # Fallback to REST - $token = if ($TokenFile) { (Get-Content $TokenFile -Raw).Trim() } else { az account get-access-token --query accessToken -o tsv } $headers = @{ Authorization = "Bearer $token"; "Content-Type" = "application/json" } - $url = "$feBase/collaborations/$collaborationId/analytics/datasets/$DatasetName/skrpolicy?api-version=2026-03-01-preview" - return Invoke-RestMethod -Uri $url -Headers $headers -Method Get -SkipCertificateCheck + $encodedCollaborationId = [Uri]::EscapeDataString($collaborationId) + $encodedDatasetName = [Uri]::EscapeDataString($DatasetName) + $url = "$feBase/collaborations/$encodedCollaborationId/analytics/datasets/$encodedDatasetName/skrpolicy?api-version=2026-03-01-preview" + try { + $policy = Invoke-RestMethod -Uri $url -Headers $headers -Method Get -ErrorAction Stop + } catch { + throw "Failed to fetch SKR policy for dataset '$DatasetName': $($_.Exception.Message)" + } + if (-not $policy.version -or @($policy.anyOf).Count -eq 0 -or -not $policy.anyOf[0]) { + throw "Frontend returned an invalid SKR policy for dataset '$DatasetName': expected version and nonempty anyOf." + } + + return $policy } # -- Process each dataset ---------------------------------------------------------- diff --git a/demos/analytics-using-managedcleanroom/scripts/11-download-output.ps1 b/demos/analytics-using-managedcleanroom/scripts/11-download-output.ps1 index d6ca398..4b2efe4 100644 --- a/demos/analytics-using-managedcleanroom/scripts/11-download-output.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/11-download-output.ps1 @@ -7,8 +7,9 @@ - SSE: Downloads via az storage blob download - CPK: Downloads via azcopy --cpk-by-value using the DEK - If -JobId is provided, filters to blobs matching that run. - Otherwise downloads the latest CSV blob. + If -JobId is provided, downloads all CSV partitions under that exact run's + Analytics/// path. Otherwise downloads all CSV outputs. + Preserves blob paths locally to avoid collisions between runs/partitions. .PARAMETER resourceGroup Azure resource group (for loading generated names). @@ -21,7 +22,8 @@ .PARAMETER JobId Optional job ID from query run (e.g., "cl-spark-"). - Filters output to this specific run. + Filters output to this specific run in both SSE and CPK modes. + Also accepts the run UUID without the cl-spark- prefix. .PARAMETER OutputDir Local directory for downloaded output (default: ./generated/output). @@ -64,87 +66,130 @@ if (-not (Test-Path $namesFile)) { . $namesFile # Detect encryption mode -$datastoreMetadataFile = Join-Path $outDir "datastores" "$persona-datastore-metadata.json" +$versionedMetadataFile = Join-Path $outDir "datastores" "$persona-datastore-metadata$datasetSuffix.json" +$datastoreMetadataFile = if (Test-Path $versionedMetadataFile) { + $versionedMetadataFile +} else { + Join-Path $outDir "datastores" "$persona-datastore-metadata.json" +} if (-not (Test-Path $datastoreMetadataFile)) { Write-Host "ERROR: '$datastoreMetadataFile' not found." -ForegroundColor Red exit 1 } $datastoreMeta = Get-Content $datastoreMetadataFile -Raw | ConvertFrom-Json -$isCpk = ($datastoreMeta.input.encryptionMode -eq "CPK") - -$outputContainer = "woodgrove-output$datasetSuffix" +$outputMeta = $datastoreMeta.output +if (-not $outputMeta.containerName -or $outputMeta.encryptionMode -notin @("SSE", "CPK")) { + throw "Output metadata must specify containerName and encryptionMode (SSE or CPK): $datastoreMetadataFile" +} +$isCpk = ($outputMeta.encryptionMode -eq "CPK") +$outputContainer = $outputMeta.containerName +$storageUrl = if ($outputMeta.storeUrl) { + $outputMeta.storeUrl.TrimEnd('/') +} else { + "https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net" +} +$storageUri = $null +if (-not [Uri]::TryCreate($storageUrl, [UriKind]::Absolute, [ref]$storageUri) -or + $storageUri.Scheme -ne "https" -or $storageUri.Query -or $storageUri.Fragment -or $storageUri.UserInfo) { + throw "Output storeUrl must be an absolute HTTPS storage endpoint without credentials, query, or fragment." +} +$storageAccountName = $storageUri.Host.Split('.')[0] +$runId = if ($JobId) { $JobId -creplace '^cl-spark-', '' } else { $null } +if ($JobId -and ([string]::IsNullOrWhiteSpace($runId) -or $runId -match '[/\\]')) { + throw "JobId must be a run ID or cl-spark-, not a path." +} Write-Host "=== Downloading query output ===" -ForegroundColor Cyan -Write-Host " Storage account: $STORAGE_ACCOUNT_NAME" -ForegroundColor Yellow +Write-Host " Storage account: $storageAccountName" -ForegroundColor Yellow Write-Host " Container: $outputContainer" -ForegroundColor Yellow Write-Host " Encryption: $(if ($isCpk) { 'CPK' } else { 'SSE' })" -ForegroundColor Yellow if ($JobId) { Write-Host " Job ID filter: $JobId" -ForegroundColor Yellow } -New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null +$blobs = az storage blob list --account-name $storageAccountName ` + --container-name $outputContainer ` + --prefix "Analytics/" --auth-mode login -o json | ConvertFrom-Json +if ($LASTEXITCODE -ne 0) { throw "Failed to list output blobs in '$outputContainer'." } + +$csvBlobs = @($blobs | Where-Object { + $segments = $_.name.Split('/') + $_.name.EndsWith('.csv', [StringComparison]::OrdinalIgnoreCase) -and + $segments.Count -ge 4 -and $segments[0] -ceq "Analytics" -and + (-not $runId -or $segments[2] -ceq $runId) +}) +if ($csvBlobs.Count -eq 0) { + Write-Host "No CSV output blobs found$(if ($JobId) { " for job '$JobId'" })." -ForegroundColor Yellow + return +} -if ($isCpk) { - # -- CPK: Download via azcopy --cpk-by-value ---------------------------------- - $dekFile = Join-Path $outDir "datastores" "keys" "woodgrove-output-csv$datasetSuffix-dek.bin" - if (-not (Test-Path $dekFile)) { - Write-Host "ERROR: DEK file '$dekFile' not found." -ForegroundColor Red - exit 1 +$downloads = @($csvBlobs | ForEach-Object { + $localFile = [IO.Path]::GetFullPath((Join-Path $OutputDir $_.name)) + $outputPrefix = $OutputDir.TrimEnd([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + + [IO.Path]::DirectorySeparatorChar + if (-not $localFile.StartsWith($outputPrefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "Output blob path escapes OutputDir: $($_.name)" } + [pscustomobject]@{ BlobName = $_.name; LocalFile = $localFile } +}) - $dekBytes = [System.IO.File]::ReadAllBytes($dekFile) - $env:CPK_ENCRYPTION_KEY = [Convert]::ToBase64String($dekBytes) - $env:CPK_ENCRYPTION_KEY_SHA256 = [Convert]::ToBase64String( - [System.Security.Cryptography.SHA256]::HashData($dekBytes)) - $env:AZCOPY_AUTO_LOGIN_TYPE = "AZCLI" - $env:AZCOPY_TENANT_ID = (az account show --query tenantId -o tsv) - - $srcUrl = "https://$STORAGE_ACCOUNT_NAME.blob.core.windows.net/$outputContainer/Analytics/*" - Write-Host " Downloading via azcopy --cpk-by-value..." -ForegroundColor Cyan - - azcopy copy $srcUrl $OutputDir --cpk-by-value --recursive --include-pattern "*.csv" 2>&1 | ForEach-Object { - Write-Host " $_" -ForegroundColor Gray +if ($isCpk) { + $dekFile = $outputMeta._local.dekFile + if (-not $dekFile -or -not (Test-Path -LiteralPath $dekFile -PathType Leaf)) { + throw "Output DEK file from metadata was not found: '$dekFile'." } - - # Cleanup env vars - Remove-Item env:CPK_ENCRYPTION_KEY -ErrorAction SilentlyContinue - Remove-Item env:CPK_ENCRYPTION_KEY_SHA256 -ErrorAction SilentlyContinue - Remove-Item env:AZCOPY_AUTO_LOGIN_TYPE -ErrorAction SilentlyContinue - Remove-Item env:AZCOPY_TENANT_ID -ErrorAction SilentlyContinue -} else { - # -- SSE: Download via az storage blob download -------------------------------- - $blobs = az storage blob list --account-name $STORAGE_ACCOUNT_NAME ` - --container-name $outputContainer ` - --prefix "Analytics/" --auth-mode login -o json | ConvertFrom-Json - - # Filter to CSV blobs (exclude .crc checksum files) - $csvBlobs = $blobs | Where-Object { - $_.name -match '\.csv$' -and $_.name -notmatch '\.crc$' + $dekBytes = Get-Content -LiteralPath $dekFile -AsByteStream -Raw + if ($dekBytes.Length -ne 32) { throw "Output DEK must contain exactly 32 bytes: $dekFile" } + + $environment = @{ + CPK_ENCRYPTION_KEY = [Convert]::ToBase64String($dekBytes) + CPK_ENCRYPTION_KEY_SHA256 = [Convert]::ToBase64String( + [System.Security.Cryptography.SHA256]::HashData($dekBytes)) + AZCOPY_AUTO_LOGIN_TYPE = "AZCLI" + AZCOPY_TENANT_ID = (az account show --query tenantId -o tsv) } - - # Optionally filter by job ID - if ($JobId) { - $runUuid = $JobId -replace '^cl-spark-', '' - $csvBlobs = $csvBlobs | Where-Object { $_.name -match $runUuid } + if ($LASTEXITCODE -ne 0 -or -not $environment.AZCOPY_TENANT_ID) { + throw "Could not determine the Azure CLI tenant for AzCopy." } + $previousEnvironment = @{} + try { + foreach ($name in $environment.Keys) { + $previousEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') + [Environment]::SetEnvironmentVariable($name, $environment[$name], 'Process') + } - if (-not $csvBlobs -or $csvBlobs.Count -eq 0) { - Write-Host "No CSV output blobs found." -ForegroundColor Yellow - exit 0 + foreach ($download in $downloads) { + New-Item -ItemType Directory -Path (Split-Path $download.LocalFile -Parent) -Force | Out-Null + $blobPath = ($download.BlobName.Split('/') | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/' + $srcUrl = "$storageUrl/$([Uri]::EscapeDataString($outputContainer))/$blobPath" + Write-Host " Downloading: $($download.BlobName)" -ForegroundColor Cyan + azcopy copy $srcUrl $download.LocalFile --cpk-by-value --overwrite=true 2>&1 | ForEach-Object { + Write-Host " $_" -ForegroundColor Gray + } + if ($LASTEXITCODE -ne 0) { throw "AzCopy failed to download '$($download.BlobName)' (exit $LASTEXITCODE)." } + } + } finally { + foreach ($name in $previousEnvironment.Keys) { + if ($null -eq $previousEnvironment[$name]) { + Remove-Item -LiteralPath "Env:$name" -ErrorAction SilentlyContinue + } else { + [Environment]::SetEnvironmentVariable($name, $previousEnvironment[$name], 'Process') + } + } } - - # Download each matching blob - foreach ($blob in $csvBlobs) { - $localFile = Join-Path $OutputDir (Split-Path $blob.name -Leaf) - Write-Host " Downloading: $($blob.name)" -ForegroundColor Cyan - az storage blob download --account-name $STORAGE_ACCOUNT_NAME ` +} else { + foreach ($download in $downloads) { + New-Item -ItemType Directory -Path (Split-Path $download.LocalFile -Parent) -Force | Out-Null + Write-Host " Downloading: $($download.BlobName)" -ForegroundColor Cyan + az storage blob download --account-name $storageAccountName ` --container-name $outputContainer ` - --name $blob.name ` - --file $localFile ` + --name $download.BlobName ` + --file $download.LocalFile ` --auth-mode login --output none + if ($LASTEXITCODE -ne 0) { throw "Failed to download '$($download.BlobName)'." } } } # Display results -$csvFiles = Get-ChildItem $OutputDir -Recurse -Filter *.csv +$csvFiles = @($downloads | ForEach-Object { Get-Item -LiteralPath $_.LocalFile }) if ($csvFiles.Count -gt 0) { Write-Host "`n=== Output ($($csvFiles.Count) CSV file(s)) ===" -ForegroundColor Green foreach ($f in $csvFiles) { diff --git a/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md b/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md index 2d01c48..f6f1d18 100644 --- a/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md +++ b/demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md @@ -1,9 +1,7 @@ # Big Data Analytics — Fast Setup Scripts (alternate scripting solution) -This guide is an **alternate, scripting-first path**: opinionated PowerShell -orchestrators that give each persona the **minimum uber-level commands** to stand -up a managed clean-room analytics collaboration. The goal: after these steps, the -**only** remaining action is running queries — and that is scripted too. +This guide is an **alternate, scripting-first path** for setting up a managed +clean-room analytics collaboration and running queries. For the step-by-step variants of the same scenario, see [README-API.md](../README-API.md) (REST via `Invoke-RestMethod` + `az rest`) and @@ -13,24 +11,41 @@ operations into per-persona orchestrators. - **Owner** = Woodgrove (creates the collaboration, publishes + runs queries) - **Collaborator** = Northwind (joins, contributes data, approves queries) -All paths are relative to `demos/analytics-using-managedcleanroom/`. +Run every command from the `demos/analytics-using-managedcleanroom/` directory, +including commands that invoke scripts in subdirectories. + +Choose one scenario: + +| Scenario | Setup participants | Query | Approval | +|---|---|---|---| +| **Single-owner (default)** | Woodgrove only | `query1`: both input views use Woodgrove's dataset | Publishing casts Woodgrove's vote; no Northwind vote | +| **Cross-party** | Woodgrove and Northwind, in separate authenticated terminals | `query2`: Northwind and Woodgrove datasets | Northwind votes after Woodgrove publishes | --- > Prerequisites: Azure CLI 2.75+, PowerShell 7+, `az login` per persona, and the > quota noted in [README-API.md](../README-API.md) Step 1.1. Acquire a per-persona > frontend token first (README Step 1.5) or set `$env:CLEANROOM_FRONTEND_TOKEN`. +> Each terminal must use its own participant's token. No `managedcleanroom` +> extension is required by this scripting path. --- ## Phase 1 — Owner creates the collaboration (control plane) ```powershell -# Deploy collaboration + enable Analytics workload + invite Northwind (one command). -./scripts/bicep/deploy-managed-cleanroom.ps1 ` - -resourceGroup cr-collab-rg -collaborationName collab1 ` - -resourceLocation westus ` - -additionalCollaborators northwind@contoso.com +$collabName = "collab1" +$deployParams = @{ + resourceGroup = "cr-collab-rg" + collaborationName = $collabName + location = "westus" + resourceLocation = "westus" + aksSku = "Standard_D4ds_v5" + nodePoolSize = 3 +} +# Cross-party only: uncomment and replace with Northwind's actual email. +# $deployParams.additionalCollaborators = @("") +.\scripts\bicep\deploy-managed-cleanroom.ps1 @deployParams ``` This is Bicep (declarative collaboration resource) + the ARM *action* steps @@ -38,96 +53,201 @@ This is Bicep (declarative collaboration resource) + the ARM *action* steps --- -## Phase 2 — Each persona provisions resources + OIDC (setup) +## Phase 2 — Each participant resolves the collaboration and joins -Run per persona (identical commands, only `$persona` differs). These are the -existing helper scripts; they create storage/KV/MI and wire OIDC. +Run this before fetching OIDC information or publishing datasets. For the +single-owner scenario only Woodgrove needs Phases 2–4. For the cross-party +scenario both participants run them in their own terminals. ```powershell +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true $persona = "woodgrove" # or "northwind" $personaRg = "cr-e2e-$persona-rg" -$collabId = "" # from Phase 3 for collaborators - -./scripts/04-prepare-resources.ps1 -resourceGroup $personaRg -persona $persona -location westus -./demos/generate-data.ps1 -persona $persona -./scripts/05-prepare-data.ps1 -resourceGroup $personaRg -variant sse -persona $persona -dataDir "./generated/datasource/$persona/csv" -datasetSuffix "-v1" -# OIDC (needs $collabId from Phase 3) -./scripts/frontend/05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -./scripts/06-setup-oidc-storage.ps1 -resourceGroup $personaRg -persona $persona -collaborationId $collabId -JwksFile "generated/$personaRg/jwks.json" -./scripts/frontend/05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -./scripts/07-grant-access.ps1 -resourceGroup $personaRg -collaborationId $collabId -contractId "Analytics" -userId $personaOid -./scripts/08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona +$collabName = "collab1" # name chosen by the owner in Phase 1 +$suffix = "-v1" # use a new suffix for a new dataset iteration + +. .\scripts\frontend\Invoke-Frontend.ps1 +$fe = Get-FrontendContext -Persona $persona +$collabId = Resolve-CollaborationId -Context $fe -CollaborationName $collabName +.\scripts\frontend\03-accept-invitation.ps1 -Persona $persona -CollaborationId $collabId + +# Use this participant's JWT oid for the federated credential. +$payload = $fe.Token.Split('.')[1].Replace('-', '+').Replace('_', '/') +$payload += '=' * ((4 - $payload.Length % 4) % 4) +$claims = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json +$personaOid = $claims.oid +if (-not $personaOid) { throw "The frontend token must contain an oid claim." } +``` + +The acceptance helper returns without accepting again if the participant is +already active (including the owner). + +--- + +## Phase 3 — Each participant provisions resources, data and OIDC + +```powershell +.\scripts\04-prepare-resources.ps1 -resourceGroup $personaRg -persona $persona -location westus +.\demos\generate-data.ps1 -persona $persona +.\scripts\05-prepare-data.ps1 -resourceGroup $personaRg -variant sse -persona $persona ` + -dataDir ".\generated\datasource\$persona\csv" -datasetSuffix $suffix +.\scripts\frontend\05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId ` + -outDir "generated\$personaRg" + +$oidcParams = @{ + resourceGroup = $personaRg + persona = $persona + collaborationId = $collabId + JwksFile = "generated\$personaRg\jwks.json" +} +# If tenant policy requires a whitelisted OIDC account, set its approved URL: +# $oidcParams.OidcStorageUrl = "https://.z22.web.core.windows.net" +.\scripts\06-setup-oidc-storage.ps1 @oidcParams +.\scripts\frontend\05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId ` + -outDir "generated\$personaRg" +.\scripts\07-grant-access.ps1 -resourceGroup $personaRg -collaborationId $collabId ` + -contractId "Analytics" -userId $personaOid -EncryptionMode SSE + +if ($persona -eq "woodgrove") { + .\scripts\08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona ` + -subdirectory "2025-09-01" +} else { + .\scripts\08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona +} ``` +For CPK encryption instead, follow the CPK upload, access, and key-preparation +steps in [README-API.md](../README-API.md). Use a distinct dataset suffix for +each iteration and a separate output directory for each query run. + --- -## Phase 3 — Collaborator joins + contributes + approves (one command) +## Phase 4 — Each participant publishes datasets -Once the owner has published a query, each collaborator runs a single -orchestrator to accept the invite, (optionally) publish their dataset, and vote: +Publish all query inputs and the owner's output dataset **before** Phase 5. +For cross-party queries, wait until both participants have completed this phase. ```powershell -# Northwind: accept invite + publish input dataset + approve the query -./scripts/frontend/run-collaborator.ps1 ` - -Persona northwind -QueryName query1-v1 ` - -DatasetDocumentId northwind-input-csv-v1 ` - -DatasetBodyFile generated/publish/northwind-input-dataset.json +.\scripts\frontend\06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` + -DocumentId "$persona-input-csv$suffix" -BodyFile "generated\publish\$persona-input-dataset.json" +if ($persona -eq "woodgrove") { + .\scripts\frontend\06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` + -DocumentId "woodgrove-output-csv$suffix" -BodyFile "generated\publish\woodgrove-output-dataset.json" +} ``` -If already onboarded and the query is published, this is literally: +--- + +## Phase 5 — Owner builds and publishes the chosen query + +**Option A — Single-owner query1** (no Northwind data or vote): ```powershell -./scripts/frontend/run-collaborator.ps1 -Persona northwind -QueryName query1-v1 +$queryName = "query1$suffix" +.\scripts\09-build-query-body.ps1 -queryName $queryName ` + -queryDir ".\demos\query\woodgrove\query1" ` + -publisherInputDataset "woodgrove-input-csv$suffix" ` + -consumerInputDataset "woodgrove-input-csv$suffix" ` + -outputDataset "woodgrove-output-csv$suffix" ``` -See [scripts/frontend/run-collaborator.ps1](frontend/run-collaborator.ps1). +**Option B — Cross-party query2** (use Northwind's exact published dataset ID; +their suffix may differ): ---- +```powershell +$northwindDataset = "" +$queryName = "query2$suffix" +.\scripts\09-build-query-body.ps1 -queryName $queryName ` + -queryDir ".\demos\query\woodgrove\query2" ` + -publisherInputDataset $northwindDataset ` + -consumerInputDataset "woodgrove-input-csv$suffix" ` + -outputDataset "woodgrove-output-csv$suffix" +``` -## Phase 4 — Owner publishes the query (once) +After choosing **one** option, publish its body: ```powershell -# Build the query body (existing helper), then publish -./scripts/09-build-query-body.ps1 -queryName query1-v1 ` - -queryDir "./demos/query/woodgrove/query1" ` - -publisherInputDataset woodgrove-input-csv-v1 ` - -consumerInputDataset woodgrove-input-csv-v1 ` - -outputDataset woodgrove-output-csv-v1 - -./scripts/frontend/07-publish-query.ps1 -Persona woodgrove -CollaborationId $collabId -QueryName query1-v1 ` - -BodyFile generated/publish/query1-v1.json +.\scripts\frontend\07-publish-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -BodyFile "generated\publish\$queryName.json" ``` Publishing casts the publisher's accept vote; remaining affected collaborators -approve (Phase 3) before execution. +approve in Phase 6 before execution. --- -## Phase 5 — Run the query (scripted, repeatable) +## Phase 6 — Northwind approves query2 (cross-party only) -After the query is approved by all collaborators, running it is one command: +Skip this phase for single-owner query1. For query2, send its exact name to +Northwind, who runs this **after publication**, using their existing terminal: ```powershell -# Run + wait for results + print run history/audit -./scripts/frontend/run-query.ps1 -Persona woodgrove -QueryName query1-v1 +$queryName = "" +.\scripts\frontend\run-collaborator.ps1 -Persona northwind -CollaborationId $collabId ` + -QueryName $queryName -SkipAccept +``` + +No dataset is published here: it was already published before the query was +proposed. The helper fetches the proposal ID and casts Northwind's vote. + +--- + +## Phase 7 — Owner runs the query and downloads output -# Download the output CSVs -./scripts/11-download-output.ps1 -resourceGroup cr-e2e-woodgrove-rg -datasetSuffix "-v1" +In Woodgrove's terminal, verify that the chosen query is accepted, then run: + +```powershell +$queryInfo = Invoke-Frontend -Context $fe -Path "$collabId/analytics/queries/$queryName" +if ($queryInfo.state -ne "Accepted") { throw "Wait for the required query approvals before running." } + +# Run + wait for completion + print run history/audit +.\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -ScaleSku small + +# Copy the job ID printed by the orchestrator; isolate this run's output. +$jobId = "" +.\scripts\11-download-output.ps1 -resourceGroup $personaRg -datasetSuffix $suffix ` + -JobId $jobId -OutputDir ".\generated\output\SSE-$jobId" ``` -Re-run any time by repeating Phase 5 — no re-setup needed. +Re-run an accepted query by repeating Phase 7 — no re-setup needed. + +Both `run-query.ps1` and `09-run-query.ps1` accept `-ScaleSku small` (default), +`medium`, or `large`; this controls the Spark execution profile, not the AKS +node-pool SKU. They also accept `-StartDate` / `-EndDate`. Check the quota and +profile details in README-API.md Step 09 before selecting a larger profile. + +A failed or submission-failed run causes the monitor and orchestrator to throw. +If submission returns no job ID, check run history before retrying rather than +assuming no run was scheduled. --- ## Cheat sheet -| Persona | Phase | Uber command | +| Persona | Phase | Commands | |---------|-------|--------------| -| Owner | 1 Create | `./scripts/bicep/deploy-managed-cleanroom.ps1 ...` | -| Both | 2 Provision + OIDC | `04-prepare-resources` → OIDC helpers | -| Collaborator | 3 Join + approve | `./scripts/frontend/run-collaborator.ps1 -Persona

-QueryName ` | -| Owner | 4 Publish query | `./scripts/frontend/07-publish-query.ps1 -Persona woodgrove -CollaborationId -QueryName -BodyFile ` | -| Owner | 5 Run query | `./scripts/frontend/run-query.ps1 -Persona woodgrove -QueryName ` | - -> Every script supports `-DryRun` to print the planned requests without calling -> the service — useful for validating a run before executing it. +| Owner | 1 Create | `deploy-managed-cleanroom.ps1` | +| Each participant | 2 Join | `Resolve-CollaborationId` → `03-accept-invitation.ps1` | +| Each participant | 3 Resources + OIDC | Resource, upload, OIDC, access and body-building helpers | +| Each participant | 4 Publish datasets | `06-publish-dataset.ps1` (Woodgrove publishes input + output) | +| Owner | 5 Publish query | `09-build-query-body.ps1` → `07-publish-query.ps1` | +| Northwind | 6 Approve query2 only | `run-collaborator.ps1 -SkipAccept` | +| Owner | 7 Execute + download | `run-query.ps1` → `11-download-output.ps1` | + +### Local request previews versus service dry runs + +Only the frontend step/orchestrator scripts and +`scripts/bicep/deploy-managed-cleanroom.ps1` support `-DryRun`. Their switch +prints planned requests instead of sending them; the ARM wrappers still read +the current Azure CLI account. Resource provisioning, upload, OIDC storage, +access, body-building, key-preparation, download and Grafana helpers do **not** +support this switch. Body builders write local files even though they do not +call the service. + +A local preview does not validate authentication, dataset contents, approval +state or effective `skuSettings`; the run helpers return only a `` +placeholder. For an actual service-side dry run, use the +`dryRun: true` request body in README-API.md Step 09; that sends a frontend +request but does not execute the Spark query. diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 b/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 index d76f2bd..fcc237c 100644 --- a/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/deploy-managed-cleanroom.ps1 @@ -40,11 +40,12 @@ skip provisioning and leave the existing collaboration as-is. .PARAMETER apiVersion - Microsoft.CleanRoom ARM API version (default: 2026-04-30-preview). + Microsoft.CleanRoom ARM API version (default: 2026-09-30-preview). .EXAMPLE ./deploy-managed-cleanroom.ps1 ` - -resourceGroup cr-collab-rg -collaborationName collab1 -resourceLocation westus + -resourceGroup cr-collab-rg -collaborationName collab1 ` + -location westus -resourceLocation westus #> param( [Parameter(Mandatory)] @@ -62,11 +63,17 @@ param( "westus", "westus2")] [string]$resourceLocation = "westus", + [ValidateSet("Standard_D4ds_v5", "Standard_D8ds_v5", "Standard_D16ds_v5", "Standard_D32ds_v5")] + [string]$aksSku = "Standard_D4ds_v5", + + [ValidateRange(3, 10)] + [int]$nodePoolSize = 3, + [string[]]$additionalCollaborators = @(), [switch]$deleteExistingCollab, - [string]$apiVersion = "2026-04-30-preview", + [string]$apiVersion = "2026-09-30-preview", [switch]$dryRun ) @@ -105,7 +112,7 @@ if ($dryRun) { Write-Host "[DRY-RUN] Would delete an existing '$collaborationName' (if present) and wait for it to vanish." } Write-Host "[DRY-RUN] Would deploy Bicep: $PSScriptRoot/managed-cleanroom.bicep (owner from caller token)" - Write-Host "[DRY-RUN] collaborationName=$collaborationName location=$location resourceLocation=$resourceLocation" + Write-Host "[DRY-RUN] collaborationName=$collaborationName location=$location resourceLocation=$resourceLocation aksSku=$aksSku nodePoolSize=$nodePoolSize" Write-Host "[DRY-RUN] Would POST $collabArmUrl/enableWorkload body {workloadType=$workloadType}" foreach ($collaborator in $additionalCollaborators) { Write-Host "[DRY-RUN] Would POST $collabArmUrl/addCollaborator body {collaborator.userIdentifier=$collaborator}" @@ -156,6 +163,8 @@ az deployment group create ` collaborationName=$collaborationName ` location=$location ` resourceLocation=$resourceLocation ` + aksSku=$aksSku ` + nodePoolSize=$nodePoolSize ` -o none if ($LASTEXITCODE -ne 0) { throw "Bicep deployment failed (az deployment group create exit code $LASTEXITCODE). See the error above." diff --git a/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep b/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep index 7801c26..8259235 100644 --- a/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep +++ b/demos/analytics-using-managedcleanroom/scripts/bicep/managed-cleanroom.bicep @@ -58,6 +58,20 @@ param location string = resourceGroup().location ]) param resourceLocation string = 'westus' +@description('Virtual machine SKU for the AKS node pool.') +@allowed([ + 'Standard_D4ds_v5' + 'Standard_D8ds_v5' + 'Standard_D16ds_v5' + 'Standard_D32ds_v5' +]) +param aksSku string = 'Standard_D4ds_v5' + +@description('Number of nodes in the AKS node pool.') +@minValue(3) +@maxValue(10) +param nodePoolSize int = 3 + @description('Optional additional collaborators added at creation time. Each entry is { userIdentifier: "" }. The owner is derived from the caller token automatically. Add further collaborators later via the addCollaborator action (see deploy script).') param collaborators array = [] @@ -66,12 +80,16 @@ param collaborators array = [] // { location, properties: { resourceLocation, collaborators[] } }) // ----------------------------------------------------------------------------- #disable-next-line BCP081 -resource collaboration 'Microsoft.CleanRoom/collaborations@2026-04-30-preview' = { +resource collaboration 'Microsoft.CleanRoom/collaborations@2026-09-30-preview' = { name: collaborationName location: location properties: { resourceLocation: resourceLocation collaborators: collaborators + targetResourceConfiguration: { + aksSku: aksSku + nodePoolSize: nodePoolSize + } } } diff --git a/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 b/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 index 3ebb621..19f97d2 100644 --- a/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/common/add-app-collaborator.ps1 @@ -3,8 +3,8 @@ Adds an app (SPN) as a collaborator to a managed cleanroom collaboration. .DESCRIPTION - Uses az rest to call the Private CleanRoom RP directly (eastus2euap ARM endpoint) - without requiring an az cloud switch. The caller must be logged in as the collaboration + Calls the production CleanRoom RP through the public Azure ARM endpoint. + The caller must be logged in as the collaboration owner (e.g., admin@contoso.com) with access to the collaboration subscription. IMPORTANT: The --user-identifier for an SPN is the Application (client) ID, @@ -23,7 +23,7 @@ Application (client) ID of the app to add as collaborator. .PARAMETER apiVersion - ARM API version (default: 2026-03-31-preview). + ARM API version (default: 2026-09-30-preview). .EXAMPLE ./scripts/common/add-app-collaborator.ps1 -collaborationName -resourceGroup -subscription "" -appClientId "" @@ -41,7 +41,7 @@ param( [Parameter(Mandatory)] [string]$appClientId, - [string]$apiVersion = "2026-03-31-preview" + [string]$apiVersion = "2026-09-30-preview" ) $ErrorActionPreference = 'Stop' @@ -55,7 +55,7 @@ if ($LASTEXITCODE -ne 0 -or -not $token) { throw "Failed to get management token. Run 'az login' first." } -$baseUrl = "https://eastus2euap.management.azure.com" +$baseUrl = "https://management.azure.com" $collabUrl = "$baseUrl/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.CleanRoom/collaborations/$collaborationName" # Step 1: Verify the collaboration exists @@ -75,7 +75,7 @@ try { # Step 2: Add the app as collaborator Write-Host "`nAdding app as collaborator..." -ForegroundColor Cyan $addUrl = "$($collabUrl)/addCollaborator?api-version=$apiVersion" -$body = @{ userIdentifier = $appClientId } | ConvertTo-Json +$body = @{ collaborator = @{ userIdentifier = $appClientId } } | ConvertTo-Json -Depth 3 try { $result = Invoke-RestMethod -Method Post -Uri $addUrl -Headers $headers -Body $body -ContentType "application/json" diff --git a/demos/analytics-using-managedcleanroom/scripts/common/prepare-resources.ps1 b/demos/analytics-using-managedcleanroom/scripts/common/prepare-resources.ps1 index 1e42717..fe56ae8 100644 --- a/demos/analytics-using-managedcleanroom/scripts/common/prepare-resources.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/common/prepare-resources.ps1 @@ -113,7 +113,7 @@ if ($existingKv) { $kvJson = $existingKv | ConvertFrom-Json Write-Host "Key Vault '$keyVaultName' already exists." -ForegroundColor Green } else { - $deletedKv = Invoke-AzSafe @("keyvault", "show-deleted", "--name", $keyVaultName) + $deletedKv = Invoke-AzSafe @("keyvault", "show-deleted", "--name", $keyVaultName, "--location", $location) if ($deletedKv) { Write-Host "Recovering soft-deleted Key Vault '$keyVaultName'..." -ForegroundColor Yellow $kvJson = az keyvault recover --name $keyVaultName --output json | ConvertFrom-Json diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/05-fetch-jwks.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/05-fetch-jwks.ps1 index b879583..a41052f 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/05-fetch-jwks.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/05-fetch-jwks.ps1 @@ -36,9 +36,9 @@ $ErrorActionPreference = "Stop" $fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun -New-Item -ItemType Directory -Path $outDir -Force | Out-Null $jwks = Invoke-Frontend -Context $fe -Path "$CollaborationId/oidc/keys" -Method GET if ($DryRun) { Write-Host "[DRY-RUN] Would write JWKS to $(Join-Path $outDir 'jwks.json')"; return } +New-Item -ItemType Directory -Path $outDir -Force | Out-Null $jwksPath = Join-Path $outDir "jwks.json" $jwks | ConvertTo-Json -Depth 10 | Out-File $jwksPath -Encoding utf8 diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 index 8701a3f..4c127d3 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/09-run-query.ps1 @@ -18,6 +18,9 @@ .PARAMETER QueryName Approved query name, e.g. "query1-v1". +.PARAMETER ScaleSku + Spark execution profile: small (default), medium, or large. + .PARAMETER StartDate Optional dataset date-range lower bound (e.g. "2025-09-01"). @@ -31,6 +34,7 @@ param( [Parameter(Mandatory)][string]$Persona, [Parameter(Mandatory)][string]$CollaborationId, [Parameter(Mandatory)][string]$QueryName, + [ValidateSet("small", "medium", "large")][string]$ScaleSku = "small", [string]$StartDate, [string]$EndDate, [string]$Frontend, @@ -43,12 +47,19 @@ $ErrorActionPreference = "Stop" $fe = Get-FrontendContext -Persona $Persona -Frontend $Frontend -TokenFile $TokenFile -DryRun:$DryRun -$runBody = @{ runId = [guid]::NewGuid().ToString() } +$runBody = @{ runId = [guid]::NewGuid().ToString(); scaleSku = $ScaleSku.ToLowerInvariant() } if ($StartDate) { $runBody.startDate = $StartDate } if ($EndDate) { $runBody.endDate = $EndDate } $runResult = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName/run" -Method POST -Body $runBody +if ($DryRun) { + Write-Host "[DRY-RUN] No run submitted. Job ID placeholder: " + return "" +} $jobId = $runResult.id +if ([string]::IsNullOrWhiteSpace([string]$jobId)) { + throw "Frontend did not return a job ID for query '$QueryName'. Submission may have succeeded; check run history before retrying." +} Write-Host "Run submitted. Job ID: $jobId" Write-Host "Track with: ./10-monitor-query.ps1 -Persona $Persona -CollaborationId $CollaborationId -JobId $jobId" return $jobId diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 index 811d927..be93828 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/10-monitor-query.ps1 @@ -4,8 +4,9 @@ .DESCRIPTION Polls the run status until COMPLETED, FAILED, or SUBMISSION_FAILED. - On a non-Ok collaboration, also prints health issues to aid triage - (e.g. CACI capacity shortages, executor pods stuck in init). + On failure, attempts to print collaboration health issues to aid triage + (e.g. CACI capacity shortages, executor pods stuck in init), then throws. + A health lookup error does not replace the original terminal run failure. Mirrors README-API.md Step 10 "Monitor Query". @@ -56,7 +57,12 @@ $result | ConvertTo-Json -Depth 10 if ($state -ne "COMPLETED") { Write-Warning "Run ended in state '$state'. Checking collaboration health for pod-level/capacity issues..." - $collabs = (Invoke-Frontend -Context $fe -Path "" -Method GET).collaborations - $health = ($collabs | Where-Object { $_.collaborationId -eq $CollaborationId }).health - if ($health) { $health | ConvertTo-Json -Depth 5 } + try { + $collabs = (Invoke-Frontend -Context $fe -Path "" -Method GET).collaborations + $health = ($collabs | Where-Object { $_.collaborationId -eq $CollaborationId }).health + if ($health) { $health | ConvertTo-Json -Depth 5 } + } catch { + Write-Warning "Could not retrieve collaboration health: $($_.Exception.Message)" + } + throw "Query run '$JobId' ended in state '$state'." } diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 index 134332f..1cc680b 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/12-get-readonly-kubeconfig.ps1 @@ -23,7 +23,7 @@ Path to write the decoded kubeconfig (default: ./readonly.kubeconfig). .PARAMETER apiVersion - Microsoft.CleanRoom ARM API version (default: 2026-04-30-preview). + Microsoft.CleanRoom ARM API version (default: 2026-09-30-preview). .EXAMPLE ./12-get-readonly-kubeconfig.ps1 -resourceGroup cr-collab-rg -collaborationName collab1 @@ -32,7 +32,7 @@ param( [Parameter(Mandatory)][string]$resourceGroup, [Parameter(Mandatory)][string]$collaborationName, [string]$OutFile = "./readonly.kubeconfig", - [string]$apiVersion = "2026-04-30-preview", + [string]$apiVersion = "2026-09-30-preview", [switch]$DryRun ) diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 index 6b42201..9ebc321 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/Invoke-Frontend.ps1 @@ -43,7 +43,7 @@ function Get-FrontendContext { ) if (-not $Frontend) { - $Frontend = "https://prod.workload-frontendwestus.cleanroom.cloudapp.azure.net" + $Frontend = "https://prod-nonattested.workload-frontendwestus.cleanroom.cloudapp.azure.net" } # Resolve the bearer token (skipped in dry-run mode). @@ -110,7 +110,6 @@ function Invoke-Frontend { Uri = $url Method = $Method Headers = $headers - SkipCertificateCheck = $true } if ($bodyJson) { $params.Body = $bodyJson diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/README.md b/demos/analytics-using-managedcleanroom/scripts/frontend/README.md index d806a2c..e2d128f 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/README.md +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/README.md @@ -9,29 +9,36 @@ deployment in `../bicep/`. | Phase | Surface | Tooling | |-------|---------|---------| -| Create collaboration, enable workload, add collaborator (Steps 02) | ARM control plane (`management.azure.com`, `2026-04-30-preview`) | `../bicep/managed-cleanroom.bicep` + `../bicep/deploy-managed-cleanroom.ps1` | +| Create collaboration, enable workload, add collaborator (Steps 02) | ARM control plane (`management.azure.com`, `2026-09-30-preview`) | `../bicep/managed-cleanroom.bicep` + `../bicep/deploy-managed-cleanroom.ps1` | | Provision storage/KV/MI, OIDC storage, data upload (Steps 04–06 helpers) | ARM + storage | `../04-*`, `../05-*`, `../06-*`, `../07-*`, `../08-*`, `../09-*` | | **Accept, publish, approve, run, monitor, results (Steps 03–12 REST)** | **Frontend / dataplane** (`...cleanroom.cloudapp.azure.net`, `2026-03-01-preview`) | **the scripts in this folder** | Bicep cannot express Steps 03–12 — they are runtime governance/dataplane operations, not resource provisioning. See `../../README-API.md` Appendix F. +Run every command below from **`demos/analytics-using-managedcleanroom/`**. +Do not change into `scripts/frontend`: generated metadata and body paths are +relative to the demo root. For a complete ordered setup, follow +[README-SCRIPTS.md](../README-SCRIPTS.md). + ## Prerequisites 1. The collaboration is created and the Analytics workload is enabled and - healthy (run `../../bicep/deploy-managed-cleanroom.ps1` first). + healthy (run `.\scripts\bicep\deploy-managed-cleanroom.ps1` first). 2. Each collaborator is authenticated and has a **frontend token** available. Token resolution order used by `Invoke-Frontend.ps1`: 1. `$env:CLEANROOM_FRONTEND_TOKEN` (SPN / CI) 2. `-TokenFile ` 3. per-persona temp file `msal-idtoken-.txt` - Acquire a per-persona token (README Step 1.5): + Acquire a per-persona token and extract its `oid` as `$personaOid` + (README Step 1.5). For the corporate-account token option: ```powershell + $persona = "woodgrove" # use "northwind" in Northwind's terminal az account get-access-token --resource "https://management.azure.com/" ` --query accessToken -o tsv | - Out-File (Join-Path $env:TEMP "msal-idtoken-woodgrove.txt") -NoNewline + Out-File (Join-Path ([System.IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt") -NoNewline ``` ## Files @@ -57,73 +64,124 @@ operations, not resource provisioning. See `../../README-API.md` Appendix F. ## Quick start — collaborator orchestrator -When the query is **already published** by the owner, a collaborator can join and -approve in one command with `run-collaborator.ps1` (chains 03 → optional 06 → 08): +For a cross-party query, Northwind must first join, configure access and publish +its input dataset. Woodgrove then publishes `query2` referencing that dataset. +Northwind can now approve the **already-published** query: ```powershell -cd scripts/frontend -# Northwind: accept invite + vote on an already-published query -./run-collaborator.ps1 -Persona northwind -QueryName query1-v1 - -# Also publish a dataset before voting -./run-collaborator.ps1 -Persona northwind -QueryName query2-v1 ` - -DatasetDocumentId northwind-input-csv-v1 ` - -DatasetBodyFile generated/publish/northwind-input-dataset.json +$collabId = "" +$queryName = "" +.\scripts\frontend\run-collaborator.ps1 -Persona northwind -CollaborationId $collabId ` + -QueryName $queryName -SkipAccept ``` -It resolves the collaboration (by `-CollaborationId`, `-CollaborationName`, or the -first visible one), tolerates an already-accepted invite, and forwards `-DryRun`. -Resource provisioning + OIDC (Steps 04–05) are prerequisites and are not run here. +Single-owner `query1` binds Woodgrove's input twice; it needs neither Northwind +data nor a Northwind vote. Publication casts Woodgrove's accept vote. + +Pass `-CollaborationId` or `-CollaborationName` explicitly to avoid the +orchestrator's first-visible-collaboration fallback. Resource provisioning and +OIDC are prerequisites and are not run by the orchestrator. Do not defer a +query's input-dataset publication until its approval step. ## Per-persona runbook (individual steps) -Set common variables in each collaborator's terminal: +Set common variables in each participant's terminal. Choose the persona +**before** deriving `$personaRg` and resolving the collaboration: ```powershell $persona = "northwind" # or "woodgrove" $personaRg = "cr-e2e-$persona-rg" -$collabId = "" # printed by 03-accept-invitation.ps1 -cd scripts/frontend +$collabName = "" +. .\scripts\frontend\Invoke-Frontend.ps1 +$fe = Get-FrontendContext -Persona $persona +$collabId = Resolve-CollaborationId -Context $fe -CollaborationName $collabName +.\scripts\frontend\03-accept-invitation.ps1 -Persona $persona -CollaborationId $collabId +``` + +Next run README Step 04 to provision resources and upload data, and Step 05 +to configure OIDC and grants. The frontend calls within Step 05 can use: + +```powershell +.\scripts\frontend\05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId ` + -outDir "generated\$personaRg" +# Run .\scripts\06-setup-oidc-storage.ps1 with this JWKS file (README Step 5.2). +.\scripts\frontend\05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId ` + -outDir "generated\$personaRg" +# Then run .\scripts\07-grant-access.ps1 (README Step 5.4). ``` +Build the dataset bodies with `.\scripts\08-build-dataset-body.ps1` as in +README Step 6.1, retaining Woodgrove's optional `2025-09-01` subdirectory. +The examples below use suffix `-v1`; replace it consistently if your upload +used a different suffix. Prepare keys after publishing if using CPK. + ### Northwind (publisher — input only) ```powershell -./03-accept-invitation.ps1 -Persona $persona -./05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -# (run ../06-setup-oidc-storage.ps1 and ../07-grant-access.ps1 per README Step 5) -./05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -# (run ../08-build-dataset-body.ps1 per README Step 6.1) -./06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` - -DocumentId "northwind-input-csv-v1" -BodyFile "generated/publish/northwind-input-dataset.json" -./08-approve-query.ps1 -Persona $persona -CollaborationId $collabId -QueryName "query2-v1" +.\scripts\frontend\06-publish-dataset.ps1 -Persona northwind -CollaborationId $collabId ` + -DocumentId "northwind-input-csv-v1" -BodyFile "generated\publish\northwind-input-dataset.json" +``` + +Send this exact dataset ID to Woodgrove and wait for the cross-party query to +be published. Then approve the query name supplied by Woodgrove: + +```powershell +$queryName = "" +.\scripts\frontend\08-approve-query.ps1 -Persona northwind -CollaborationId $collabId -QueryName $queryName ``` ### Woodgrove (owner — input + output, publishes/runs query) +Use Woodgrove's own terminal, token and resource metadata from the common steps. +Publish both datasets: + +```powershell +.\scripts\frontend\06-publish-dataset.ps1 -Persona woodgrove -CollaborationId $collabId ` + -DocumentId "woodgrove-input-csv-v1" -BodyFile "generated\publish\woodgrove-input-dataset.json" +.\scripts\frontend\06-publish-dataset.ps1 -Persona woodgrove -CollaborationId $collabId ` + -DocumentId "woodgrove-output-csv-v1" -BodyFile "generated\publish\woodgrove-output-dataset.json" +``` + +Build **either** the single-owner `query1-v1` body or the cross-party `query2-v1` +body with `.\scripts\09-build-query-body.ps1` (README Step 7.1). Query2 requires +Northwind's dataset to have been published already. Publish the chosen body: + +```powershell +$queryName = "query1-v1" # or "query2-v1" if you built the cross-party body +.\scripts\frontend\07-publish-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -BodyFile "generated\publish\$queryName.json" +``` + +For query2, wait for Northwind's vote before continuing. Query1 needs no extra +vote. Check approval and execute: + ```powershell -$persona = "woodgrove" -./03-accept-invitation.ps1 -Persona $persona -./05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -./05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId -outDir "generated/$personaRg" -./06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` - -DocumentId "woodgrove-input-csv-v1" -BodyFile "generated/publish/woodgrove-input-dataset.json" -./06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId ` - -DocumentId "woodgrove-output-csv-v1" -BodyFile "generated/publish/woodgrove-output-dataset.json" -# (build query body via ../09-build-query-body.ps1 per README Step 7.1) -./07-publish-query.ps1 -Persona $persona -CollaborationId $collabId ` - -QueryName "query1-v1" -BodyFile "generated/publish/query1-v1.json" -./08-approve-query.ps1 -Persona $persona -CollaborationId $collabId -QueryName "query1-v1" -$jobId = (./09-run-query.ps1 -Persona $persona -CollaborationId $collabId -QueryName "query1-v1") -./10-monitor-query.ps1 -Persona $persona -CollaborationId $collabId -JobId $jobId -./11-results-audit.ps1 -Persona $persona -CollaborationId $collabId -QueryName "query1-v1" -# then download output via ../11-download-output.ps1 (README Step 11.3) -./12-get-readonly-kubeconfig.ps1 -resourceGroup -collaborationName +$queryInfo = Invoke-Frontend -Context $fe -Path "$collabId/analytics/queries/$queryName" +if ($queryInfo.state -ne "Accepted") { throw "Wait for the required query approvals before running." } +$jobId = .\scripts\frontend\09-run-query.ps1 -Persona woodgrove -CollaborationId $collabId ` + -QueryName $queryName -ScaleSku small +.\scripts\frontend\10-monitor-query.ps1 -Persona woodgrove -CollaborationId $collabId -JobId $jobId +.\scripts\frontend\11-results-audit.ps1 -Persona woodgrove -CollaborationId $collabId -QueryName $queryName +.\scripts\11-download-output.ps1 -resourceGroup $personaRg -datasetSuffix "-v1" ` + -JobId $jobId -OutputDir ".\generated\output\$jobId" +.\scripts\frontend\12-get-readonly-kubeconfig.ps1 -resourceGroup "" -collaborationName "" ``` ## Notes -- All scripts accept optional `-Frontend` and `-TokenFile` overrides. +- Frontend scripts accept optional `-Frontend` and `-TokenFile` overrides; + the ARM-only kubeconfig helper does not. An environment token takes + precedence over `-TokenFile` in the shared frontend helper. - `06-publish-dataset.ps1 -DisableConsent` toggles execution consent off. -- `09-run-query.ps1` accepts `-StartDate` / `-EndDate` for date-range filtering. -- `10-monitor-query.ps1` dumps collaboration `health` on any non-`COMPLETED` run. +- `09-run-query.ps1` and `run-query.ps1` accept `-ScaleSku small` (default), + `medium`, or `large`, and `-StartDate` / `-EndDate` for date-range filtering. + The Spark execution profile is separate from the collaboration's AKS SKU. +- Both run helpers stop if the frontend response has no job ID. Check run + history before retrying: the service may already have scheduled the query. +- `10-monitor-query.ps1` throws on `FAILED` or `SUBMISSION_FAILED` after a + best-effort collaboration-health lookup. The orchestrator stops instead of + reporting successful completion. +- `-DryRun` on these frontend scripts previews requests locally; it does not + send the service-side `dryRun: true` request or validate `skuSettings`. + Run helpers return `` for a local preview, not an actual submitted run. + The kubeconfig helper still reads the current Azure CLI account. diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 index 9ca2662..fc702dd 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/run-collaborator.ps1 @@ -28,7 +28,7 @@ Collaborator persona (selects the token file), e.g. northwind. .PARAMETER QueryName - The already-published query to vote on, e.g. "query1-v1". + The already-published cross-party query to vote on, e.g. "query2-v1". .PARAMETER CollaborationId Frontend collaboration UUID. If omitted, resolved via -CollaborationName or @@ -59,8 +59,8 @@ Print planned requests without calling the service. .EXAMPLE - # Northwind joins and approves an already-published query - ./run-collaborator.ps1 -Persona northwind -QueryName query1-v1 + # Northwind approves an already-published cross-party query + ./run-collaborator.ps1 -Persona northwind -QueryName query2-v1 -SkipAccept .EXAMPLE # Also publish a dataset before voting @@ -104,12 +104,7 @@ Write-Host "==> Collaboration: $CollaborationId" # --------------------------------------------------------------------------- if (-not $SkipAccept) { Write-Host "==> Accepting invitation..." - try { - & "$PSScriptRoot/03-accept-invitation.ps1" @childArgs -CollaborationId $CollaborationId - } - catch { - Write-Warning "Accept step skipped/failed (may already be accepted): $($_.Exception.Message)" - } + & "$PSScriptRoot/03-accept-invitation.ps1" @childArgs -CollaborationId $CollaborationId } # --------------------------------------------------------------------------- diff --git a/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 b/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 index e236fdf..4fbaf75 100644 --- a/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 +++ b/demos/analytics-using-managedcleanroom/scripts/frontend/run-query.ps1 @@ -13,12 +13,12 @@ 2. (optional) Publish the query (07) when -BodyFile is supplied. NOTE: after publishing, every affected collaborator must approve it (run-collaborator.ps1 / 08-approve-query.ps1) before it can run. - 3. Run the query (capturing the job id). + 3. Verify the query is Accepted, then run it (capturing the job id). 4. (optional) Monitor to a terminal state (10). 5. (optional) Print run history + audit events (11). Output download (README Step 11.3) is left to ../11-download-output.ps1 - because it needs the per-persona resource group. + because it needs the per-persona resource group and dataset suffix. .PARAMETER Persona Owner persona (selects the token file), e.g. woodgrove. @@ -36,6 +36,9 @@ .PARAMETER BodyFile Optional query body JSON to publish before running (invokes 07). +.PARAMETER ScaleSku + Spark execution profile: small (default), medium, or large. + .PARAMETER StartDate Optional dataset date-range lower bound (e.g. "2025-09-01"). @@ -62,7 +65,8 @@ ./run-query.ps1 -Persona woodgrove -QueryName query1-v1 .EXAMPLE - # Publish then run (remember collaborators must approve between the two) + # Publish then run a single-owner query (publication casts the owner's vote). + # A cross-party query must be published and approved separately before running. ./run-query.ps1 -Persona woodgrove -QueryName query1-v1 ` -BodyFile generated/publish/query1-v1.json #> @@ -72,6 +76,7 @@ param( [string]$CollaborationId, [string]$CollaborationName, [string]$BodyFile, + [ValidateSet("small", "medium", "large")][string]$ScaleSku = "small", [string]$StartDate, [string]$EndDate, [switch]$SkipMonitor, @@ -101,16 +106,27 @@ if ($BodyFile) { Write-Host "==> Publishing query '$QueryName'..." & "$PSScriptRoot/07-publish-query.ps1" @childArgs -CollaborationId $CollaborationId ` -QueryName $QueryName -BodyFile $BodyFile - Write-Host " (collaborators must now approve via run-collaborator.ps1 / 08-approve-query.ps1)" + Write-Host " (the publisher's vote is automatic; remaining affected collaborators must approve)" +} + +# 3. Check approval before submitting a run. +if (-not $DryRun) { + $queryInfo = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName" + if ($queryInfo.state -ne "Accepted") { + throw "Query '$QueryName' is not Accepted (state='$($queryInfo.state)'). Obtain the required approvals, then rerun without -BodyFile." + } } -# 3. Run the query (capture the job id). +# Run the query (capture the job id). Write-Host "==> Running query '$QueryName'..." -$runBody = @{ runId = [guid]::NewGuid().ToString() } +$runBody = @{ runId = [guid]::NewGuid().ToString(); scaleSku = $ScaleSku.ToLowerInvariant() } if ($StartDate) { $runBody.startDate = $StartDate } if ($EndDate) { $runBody.endDate = $EndDate } $runResult = Invoke-Frontend -Context $fe -Path "$CollaborationId/analytics/queries/$QueryName/run" -Method POST -Body $runBody $jobId = if ($DryRun) { "" } else { $runResult.id } +if ([string]::IsNullOrWhiteSpace([string]$jobId)) { + throw "Frontend did not return a job ID for query '$QueryName'. Submission may have succeeded; check run history before retrying." +} Write-Host " Job ID: $jobId" # 4. Monitor (optional). @@ -122,9 +138,17 @@ if (-not $SkipMonitor) { # 5. Results + audit (optional). if (-not $SkipResults) { Write-Host "==> Fetching run history + audit events..." - & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId -QueryName $QueryName + if ($DryRun) { + & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId -QueryName $QueryName | Out-Null + } else { + & "$PSScriptRoot/11-results-audit.ps1" @childArgs -CollaborationId $CollaborationId -QueryName $QueryName + } } Write-Host "" +if ($DryRun) { + Write-Host "[DRY-RUN] Workflow preview complete; no query was submitted." + return $jobId +} Write-Host "Query workflow complete for '$QueryName' (job $jobId) on collaboration $CollaborationId." -Write-Host "Download output with: ../11-download-output.ps1 -resourceGroup -JobId $jobId" +Write-Host "From the demo root, download with: .\scripts\11-download-output.ps1 -resourceGroup -datasetSuffix -JobId $jobId" diff --git a/demos/analytics-using-managedcleanroom/tsg/customer/index.md b/demos/analytics-using-managedcleanroom/tsg/customer/index.md index 3e160b5..f190dfb 100644 --- a/demos/analytics-using-managedcleanroom/tsg/customer/index.md +++ b/demos/analytics-using-managedcleanroom/tsg/customer/index.md @@ -9,9 +9,9 @@ Issues extracted from the [REST API guide](../../README-API.md) and [CLI guide]( | # | Issue | Error / Symptom | Cause | Fix | Step | |---|---|---|---|---|---| -| 1 | Quota insufficient | Collaboration creation or query execution fails | Subscription lacks minimum vCPU quota in the `$resourceLocation` region | Ensure at least 8 vCPUs Ddsv5 (AKS) + 6 vCPUs Confidential ACI. Add 4 Ddsv5 per additional concurrent query. | Step 01 | +| 1 | Quota insufficient | Collaboration creation or query execution fails | Subscription lacks minimum vCPU quota in the `$resourceLocation` region | Ensure at least 12 vCPUs Ddsv5 (AKS) + 6 vCPUs Confidential ACI. Allow up to 6 additional Confidential ACI vCPUs per concurrent `small` query. | Step 01 | | 2 | RP role assignment required | ARM operations fail due to missing permissions | RP App requires User Access Administrator on the subscription | `az role assignment create --assignee "d76bde86-0387-4db5-af46-51a9e31e6666" --role "User Access Administrator" --scope "/subscriptions/$subscription"` | Step 01 | -| 3 | Python 3.13 tuple error (CLI only) | CLI commands fail with tuple error | CLI extension bug in older versions | Upgrade to `managedcleanroom` extension v1.0.0b6+ | Any CLI step | +| 3 | Python 3.13 tuple error (CLI only) | CLI commands fail with tuple error | CLI extension bug in older versions | Upgrade to `managedcleanroom` extension `1.0.0b10` | Any CLI step | ## Identity & Federated Credentials @@ -33,7 +33,7 @@ Issues extracted from the [REST API guide](../../README-API.md) and [CLI guide]( | # | Issue | Error / Symptom | Cause | Fix | Step | |---|---|---|---|---|---| -| 10 | SSL certificate verify failed | `SSL certificate verify failed` | Endpoint cert mismatch | **API**: `-SkipCertificateCheck` (in `Invoke-Frontend`). **CLI**: `$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION = "1"` | Any frontend call | +| 10 | SSL certificate verify failed | `SSL certificate verify failed` | Wrong or stale frontend endpoint | Configure the non-attested endpoint explicitly and keep TLS verification enabled | Any frontend call | | 11 | NSG blocking AKS endpoint | Query execution times out | Tenant NSGs block inbound port 443 to AKS | Contact ACCR team with `tenantId` to whitelist tenant | Step 09 | | 12 | AVNM blocking connectivity | Query execution times out | Azure Virtual Network Manager tenant policy blocks port 443 | Tenant admin must create AVNM rule to allow port 443 from internet | Step 09 |