Engineer an ML sandbox for external researchers with resource quotas, dataset masking,…
- User
Engineer an ML sandbox for external researchers with resource quotas, dataset masking, and monitoring.
- Assistant
Engineer an ML sandbox for external researchers with resource quotas, dataset masking, and monitoring.
We are asked: "Engineer an ML sandbox for external researchers with resource quotas, dataset masking, and monitoring."
We need to design and possibly implement an ML sandbox, likely a system that allows external researchers (i.e., from outside the organization) to run machine learning experiments on the organization's data and compute resources, but with constraints: resource quotas (so they can't use too much CPU/GPU, memory, storage, time, etc.), dataset masking (so they can only see certain columns or transformed data for privacy/security), and monitoring (so the organization can track usage, results, possibly for auditing and billing).
We need to produce a comprehensive answer: architecture, components, technologies, possibly sample code. This is a system design question. Possibly they want us to think about building a platform similar to Google Colab or AWS SageMaker but with restrictions.
We need to consider:
We should propose a high-level architecture:
Implementation details:
We may also consider:
We need to produce an answer that covers these aspects.
They said "Engineer an ML sandbox for external researchers". This implies we are building the system, not just designing. Could be high-level design, maybe with some sample code for quota enforcement or masking. But it's an open-ended prompt. Typically, ChatGPT would output a comprehensive solution with architecture diagram descriptions, component choices, and maybe code snippets.
I will structure the answer as:
I'll also emphasize the integration between components.
Let's flesh out details.
We need to provide a secure, controlled environment where external researchers can run ML experiments on organizational data without exposing sensitive information and without overusing resources. The sandbox should be easy to access (via web browser), provide common ML tools, and support dataset discovery, masking, and resource limits.
Assume cloud-native, container-based. Use Kubernetes cluster (could be on AWS/EKS, GCP/GKE, Azure/AKS, or on-prem). JupyterHub for interactive notebooks. All user workloads run as pods in K8s. Data stored in object storage (S3) or a database. Identity provider (Keycloak) for auth. Monitoring stack (Prometheus, Grafana, Loki). Experiment tracking: MLflow. Data masking: a service that transforms datasets on the fly, or pre-masked datasets served via a differential privacy engine or view.
Data flow:
researcher can access limited datasets, start notebooks within quota. admin manages quotas, datasets, monitoring. Use Kubernetes RBAC to restrict what users can do; but since users only interact via JupyterHub, they don't have direct K8s access. The control plane (JupyterHub) creates pods on behalf of users with appropriate labels and namespace.singleuser image with ML stack (TensorFlow, PyTorch, scikit-learn, etc.).kubespawner to set cpu_guarantee, cpu_limit per user based on a config map that maps usernames to quotas. More flexible: use an admission controller or custom spawner that consults an external quota service.idle_timeout and cull to stop idle notebooks.Use K8s ResourceQuota objects at the namespace level. Since each user could have their own namespace (created by JupyterHub spawner), we can apply quotas there. Alternatively, use a single namespace with LimitRange and ResourceQuota but that aggregates across users, so need separation.
K8s ResourceQuota can limit:
requests.cpu, requests.memorylimits.cpu, limits.memoryrequests.storage (sum of PVC sizes)count/pods (max number of pods)For GPU: Use limits.nvidia.com/gpu (if using Nvidia GPUs and device plugin). Also can set limits for other resources.
Time-based quotas: K8s doesn't natively enforce time limits, but we can use activeDeadlineSeconds in the pod spec (set by spawner). Or have a controller that monitors pod age and deletes if exceeds quota. Or use tools like kube-usage or kubecost for tracking, but enforcement via termination.
For cluster-wide quotas: Use ResourceQuota on the whole cluster? Actually, K8s ResourceQuota is per namespace. To enforce per-user across all namespaces, we need a separate tool. Could use kube quotas per namespace as above. If each user has a dedicated namespace, that's fine.
Approach: JupyterHub creates a Kubernetes namespace for each user (or for each project). Then we apply a ResourceQuota in that namespace with limits based on the user's assigned quota (retrieved from a database). This can be automated via a custom hook.
Dataset catalog: Store metadata about datasets (name, description, original location, sensitivity level, masking rules). This could be a database (PostgreSQL) or a simple file.
When a user requests a dataset (e.g., via a UI in JupyterHub), the system checks the user's permissions. Permission may be based on user group or dataset access list.
For masking: If the dataset is a database table, we can create a view with masking (e.g., replace PII with tokens, generalize ages, etc.) and grant the user access only to that view. Use database row-level security (RLS) or column-level security.
If dataset is files (CSV, Parquet) in object storage, we can generate a masked copy on the fly when user accesses. Could use a service that runs in the user's pod (a sidecar) that intercepts file reads and masks. Simpler: pre-generate masked versions and store them in a separate bucket, and user gets read-only access to that bucket. The masking process may be one-time or dynamic (if policy changes).
Implementation: Use a masking microservice (Python) that receives dataset name and user ID, checks policies, and either returns a masked dataset (by reading source, applying transforms) or returns a signed URL to a masked file in object storage. The notebook can then download or mount the bucket.
To integrate with notebooks: Provide a Python library sandbox_data with functions like load_dataset(name) that handles masking transparently. The library communicates with the masking service using the user's auth token.
Masking rules: Could be defined per dataset, e.g., mask columns: ssn -> hash, email -> pseudonymize. Or apply differential privacy (add noise). Could use open-source tools like ARX, Amnesia, or custom scripts.
Security: The original data should never be exposed to the user's pod. Only masked data is accessible. The masking service should run in a secure zone with access to original data, but the user's pod only has access to masked output (via a separate storage location). Use Kubernetes network policies to ensure the user pod cannot access the original data storage (i.e., only the masking service can).
Goals: Track resource usage (CPU, memory, GPU, storage, network), dataset access, user activity, errors, audit for compliance.
Metrics: Use Prometheus to collect metrics from:
Logs: Use Fluentd or Fluent Bit as daemonset to collect container logs and ship to Loki or Elasticsearch. Include labels (username, namespace) for filtering.
Dashboards: Grafana with pre-built dashboards for resource usage per user, dataset access logs, quota consumption, cluster health.
Audit logs: Also send to a secure immutable store (e.g., AWS S3 with object lock) for long-term retention.
Experiment tracking: MLflow Tracking Server deployed in the cluster. Users can log experiments via MLflow client in notebooks. MLflow stores parameters, metrics, and artifacts (like model files) in a backend (e.g., MySQL database + S3). This gives visibility into what experiments are being run.
Alerts: Set up alert rules (via Prometheus Alertmanager) for quota overrun, unusual activity (e.g., pod trying to access external network), or data exfiltration attempts.
kube-capacity or kubecost for cost allocation.raw/ for original data (restricted), masked/ for public datasets.masked/ bucket or streams on request. Deploy it in the cluster with strict network policies; only JupyterHub or user pods can call it via internal endpoint.load_dataset Python library that calls the masking service.post-spawn hook to apply a quota YAML based on user's allowed quota (from a config DB). Also set up LimitRange for default requests/limits.apiVersion: v1
kind: ResourceQuota
metadata:
name: user-quota
namespace: user-alice
spec:
hard:
requests.cpu: "2"
requests.memory: 8Gi
limits.cpu: "4"
limits.memory: 16Gi
requests.nvidia.com/gpu: "1"
requests.storage: "50Gi"
count/pods: "5"
We can generate this dynamically based on user's quota.
jupyterhub:
hub:
extraConfig:
01-quota: |
async def post_spawn_hook(spawner):
import os
import kubernetes_asyncio as k8s
from jupyterhub.utils import make_ssl_context
namespace = spawner.user.name
# Ensure namespace exists (created by JupyterHub automatically if configured)
# Apply ResourceQuota
quota = k8s.client.V1ResourceQuota(
metadata=k8s.client.V1ObjectMeta(name="user-quota", namespace=namespace),
spec=k8s.client.V1ResourceQuotaSpec(
hard={
"requests.cpu": "2",
"requests.memory": "8Gi",
"limits.cpu": "4",
"limits.memory": "16Gi",
"requests.storage": "50Gi",
"count/pods": "5"
}
)
)
async with spawner.api.apps['k8s'].api() as api:
try:
await api.create_namespaced_resource_quota(namespace, quota)
except k8s.rest.ApiException as e:
if e.status != 409: # Already exists
raise
# Also set activeDeadlineSeconds for pod
spawner.extra_pod_config = {
"activeDeadlineSeconds": 86400, # 24 hours
}
custom:
# Use a custom spawner that sets per-user resource limits based on a config map
# Could also use KubeSpawner's resource limits config
But note: JupyterHub by default creates a namespace per user if using KubeSpawner with user_namespace set. Actually, the hub itself creates a namespace for each user when using KubeSpawner with user_namespace=True (default is True? Need to check). Actually, the default for KubeSpawner is to create a unique pod_name but not namespace. To have isolated namespaces, you need to set user_namespace=True and the hub must have permission to create namespaces. That is possible.
Better: Use KubeSpawner with user_namespace=True and configure a extra_pod_config for resource limits? Actually, resource limits are set at pod spec level (spec.containers[0].resources). That can be set per spawner via cpu_limit, mem_limit, etc. But those are per pod, not aggregated across pods. To enforce aggregate, need namespace quotas.
So we need to create a namespace per user and apply a ResourceQuota. JupyterHub can be configured to do that via a post_spawn_hook. Also, we need to set activeDeadlineSeconds at pod level to enforce max lifetime. That can be set in extra_pod_config.
# masking_service.py
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import OAuth2AuthorizationCodeBearer
import pandas as pd
import os
from typing import List
app = FastAPI()
# OIDC token validation would be here (simplified)
oauth2_scheme = OAuth2AuthorizationCodeBearer(tokenUrl="token", authorizationUrl="authorize")
# Mock dataset registry and masking rules
DATASETS = {
"users": {
"source": "s3://raw-bucket/users.csv",
"masking_rules": {
"ssn": "hash",
"email": "pseudonymize",
"dob": " generalize(age, 5)"
}
}
}
def apply_masking(df: pd.DataFrame, rules: dict) -> pd.DataFrame:
for col, rule in rules.items():
if col not in df.columns:
continue
if rule == "hash":
df[col] = df[col].apply(lambda x: hash(str(x)) % 10**10)
elif rule == "pseudonymize":
# In real life, use a secret key and consistent mapping
df[col] = df[col].apply(lambda x: "user_" + str(hash(str(x)) % 100000))
elif rule.startswith("generalize"):
# Example: generalize column to buckets of size 5
if col == "age":
df[col] = (df[col] // 5) * 5
return df
@app.get("/datasets/{name}")
async def get_dataset(name: str, token: str = Depends(oauth2_scheme)):
# Validate token (skip for example)
if name not in DATASETS:
raise HTTPException(status_code=404, detail="Dataset not found")
dataset = DATASETS[name]
# Read source from S3 (simulate)
# In real code, use boto3
df = pd.read_csv(dataset["source"]) # using local path for demo
masked_df = apply_masking(df, dataset["masking_rules"])
# Write to a temporary file or return as JSON/CSV
# For simplicity, return CSV as string
csv_data = masked_df.to_csv(index=False)
return {"data": csv_data}
In a real system, we would store the masked version in object storage and return a presigned URL, to avoid streaming large data through the service.
User code in notebook:
import requests
token = get_token_somehow() # from JupyterHub environment
response = requests.get("http://masking-service.internal/datasets/users", headers={"Authorization": f"Bearer {token}"})
csv_data = response.json()["data"]
df = pd.read_csv(io.StringIO(csv_data))
Better: Provide a library that handles token automatically by reading from JupyterHub's API token environment variable.
scrape_configs:
- job_name: 'jupyterhub'
static_configs:
- targets: ['hub-service:8081'] # JupyterHub's metrics endpoint
JupyterHub exposes metrics at /metrics when configured with prometheus in its config.
groups:
- name: quota_alerts
rules:
- alert: UserNamespaceQuotaExceeded
expr: sum(kube_resource_quota{resource="requests.cpu", namespace=~"user-.*"}) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "User namespace {{ $labels.namespace }} has exceeded CPU quota"
But better to use kube_resource_quota metric if available, or compute from kube_pod_container_resource_requests. Might need custom exporter.
LimitRanges to set default limits, and monitor actual usage; if a pod exceeds its limit, it gets throttled or OOM killed. Also use cgroups. Could set requests equal to limits for strict enforcement, but that reduces flexibility. Alternatively, use a custom scheduler or use tools like Gเค'อ'VISA (not sure). Another approach: Use kubectl top to monitor and kill overages.kubecost or custom script to compute based on node pricing and usage.Summarize that the proposed architecture meets requirements: quotas via K8s, masking via dedicated service, monitoring via Prometheus and MLflow, and security via isolation. It's scalable and uses open-source components.
We can also mention that we could extend to support model deployment in a separate environment, but not needed for sandbox.
I will produce the final answer accordingly.
We need to provide a secure, self‑service ML sandbox where external researchers can:
The solution must be:
+-------------------+
| External |
| Researcher |
+--------+----------+
| HTTPS (OIDC)
v
+-------------------+ +-------------------+
| JupyterHub / | | Authentication |
| Portal (Web) +<---->+ (Keycloak) |
+--------+----------+ +-------------------+
|
| Creates pods in dedicated namespaces
v
+---------------------------------------------------+
| Kubernetes Cluster |
| +------------------+ +-----------------------+ |
| | User Namespace | | Masking Service | |
| | (per researcher) | | (transforms raw data) | |
| +--------+---------+ +----------+------------+ |
| | | |
| +--------+---------+ +----------+------------+ |
| | Notebook Pod | | Masked Data Bucket | |
| | (ML stack) | | (read‑only) | |
| +--------+---------+ +-----------------------+ |
+---------------------------------------------------+
|
| Metrics & Logs
v
+-------------------+ +-------------------+
| Monitoring | | Experiment |
| (Prometheus, | | Tracking |
| Grafana, Loki) | | (MLflow) |
+-------------------+ +-------------------+
researcher.hub service account).KubeSpawner with:
user_namespace=True → each user gets a dedicated K8s namespace. Namespace is deleted when user is removed.extra_pod_config:
{
"activeDeadlineSeconds": 86400, # max pod lifetime 24h
"terminationGracePeriodSeconds": 30,
}
ml-sandbox-notebook) with:
mlflow, boto3, and a client library sandbox_data for loading masked datasets.ResourceQuota and LimitRange objects.quota_db) and creates:
apiVersion: v1
kind: ResourceQuota
metadata:
name: user-quota
namespace: user-{{username}}
spec:
hard:
requests.cpu: "2"
requests.memory: "8Gi"
limits.cpu: "4"
limits.memory: "16Gi"
requests.nvidia.com/gpu: "1" # if GPU needed
requests.storage: "50Gi" # PVC for user data
count/pods: "5" # max simultaneous pods
requests; limits enforce throttling/OOM.activeDeadlineSeconds kills pod after 24h; notebooks also auto‑cull after inactivity (cull_idle_timeout).kubecost).s3://raw-bucket) with IAM policy denying all user namespaces.s3://masked-bucket).hash (salt‑ed cryptographic hash)pseudonymize (consistent reversible mapping with secret key)generalize (e.g., age→5‑year buckets)suppress (remove column)GET /datasets/{name} → applies masking on‑the‑fly, writes result to masked bucket, returns a presigned URL (valid 1h) to the user.# In notebook
from sandbox_data import load_dataset
df = load_dataset("users") # automatically uses JupyterHub token, calls masking service, returns pandas DataFrame
raw-bucket. They only have read access to masked-bucket via a dedicated service account. Network policies block egress from user pods to raw bucket endpoints.node-exporter), cAdvisor (container resource usage)./metrics endpoint).kube-resource-quota metrics).user, namespace).mlflow.set_tracking_uri("http://mlflow:5000")).runAsNonRoot: true, readOnlyRootFilesystem: true where possible.allowPrivilegeEscalation: false, seccompProfile: RuntimeDefault.kubectl access for users; all actions via JupyterHub UI.helm repo add jupyterhub https://hub.jupyter.org/helm-chart/
helm upgrade --install jhub jupyterhub/jupyterhub \
--namespace jhub --create-namespace \
--values values.yaml
Configure KubeSpawner, OIDC, post‑spawn hook for quota.raw-bucket (ACL: only masking service) and masked-bucket (read for user service accounts).sandbox_data Python client (pip installable) and include in notebook image.ResourceQuota + LimitRange.prometheus-operator (kube‑prometheus‑stack) for metrics.loki + fluent-bit for logs.helm repo add mlflow https://community.charts.iriskline.com
helm install mlflow mlflow/mlflow --set backendStore.uri=mysql://... --set artifactRoot=s3://masked-bucket/mlflow
# in jupyterhub_config.py
import os
import yaml
from kubernetes_asyncio import client as k8s
async def apply_user_quota(spawner):
namespace = spawner.user.name
# Fetch quota limits from a simple config map or DB (here hard‑coded)
quota_spec = {
"hard": {
"requests.cpu": "2",
"requests.memory": "8Gi",
"limits.cpu": "4",
"limits.memory": "16Gi",
"requests.storage": "50Gi",
"count/pods": "5"
}
}
quota = k8s.V1ResourceQuota(
metadata=k8s.V1ObjectMeta(name="user-quota", namespace=namespace),
spec=k8s.V1ResourceQuotaSpec(**quota_spec)
)
async with spawner.api.apps['k8s'].api() as api:
try:
await api.create_namespaced_resource_quota(namespace, quota)
except k8s.rest.ApiException as e:
if e.status != 409: # 409 = AlreadyExists
raise
c.JupyterHub.hooks = ["post_spawn"]
c.JupyterHub.post_spawn_hook = apply_user_quota
# masking_service.py
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import OAuth2AuthorizationCodeBearer
import pandas as pd
import boto3
import io
import os
from typing import Dict
app = FastAPI()
oauth2_scheme = OAuth2AuthorizationCodeBearer(tokenUrl="token", authorizationUrl="authorize")
# Database of datasets and rules (in real life, use a real DB)
DATASETS = {
"customers": {
"source": "s3://raw-bucket/customers.parquet",
"masking_rules": {
"ssn": "hash",
"email": "pseudonymize",
"birth_date": "generalize(5)"
}
}
}
S3 = boto3.client("s3")
RAW_BUCKET = "raw-bucket"
MASKED_BUCKET = "masked-bucket"
def apply_masking(df: pd.DataFrame, rules: Dict[str, str], secret_salt: str = "my-secret") -> pd.DataFrame:
for col, rule in rules.items():
if col not in df.columns:
continue
if rule == "hash":
df[col] = df[col].astype(str).apply(lambda x: hash(secret_salt + x) % 10**10)
elif rule == "pseudonymize":
# Deterministic mapping using secret key
df[col] = df[col].astype(str).apply(lambda x: f"user_{hash(secret_salt + x) % 1000000}")
elif rule.startswith("generalize"):
# e.g., generalize(5) → bucket size 5 years
bucket = int(rule.split("(")[1].rstrip(")"))
if col in ["age", "birth_date"]:
if col == "birth_date":
# convert to age assuming current year=2025
birth_year = pd.to_datetime(df[col]).dt.year
age = 2025 - birth_year
df[col] = (age // bucket) * bucket
else:
df[col] = (df[col] // bucket) * bucket
return df
@app.get("/datasets/{name}")
async def get_dataset(name: str, token: str = Depends(oauth2_scheme)):
# TODO: validate token, check user permissions for dataset
if name not in DATASETS:
raise HTTPException(status_code=404, detail="Dataset not found")
ds = DATASETS[name]
# Download raw data from S3
obj = S3.get_object(Bucket=RAW_BUCKET, Key=ds["source"].split("/")[-1])
if ds["source"].endswith(".parquet"):
df = pd.read_parquet(io.BytesIO(obj["Body"].read()))
else:
df = pd.read_csv(io.BytesIO(obj["Body"].read()))
# Apply masking
df_masked = apply_masking(df, ds["masking_rules"])
# Write masked version to masked bucket (or stream directly)
masked_key = f"{name}/masked.parquet"
out_buffer = io.BytesIO()
df_masked.to_parquet(out_buffer, index=False)
out_buffer.seek(0)
S3.put_object(Bucket=MASKED_BUCKET, Key=masked_key, Body=out_buffer.getvalue())
# Generate presigned URL (valid 1 hour)
url = S3.generate_presigned_url(
ClientMethod="get_object",
Params={"Bucket": MASKED_BUCKET, "Key": masked_key},
ExpiresIn=3600,
)
return {"url": url, "format": "parquet"}
User‑side helper:
# sandbox_data/__init__.py
import os
import requests
from notebook import notebookapp as app
def get_jupyter_token():
# Find the running notebook server and extract the token
servers = list(app.list_running_servers())
if not servers:
raise RuntimeError("No running Jupyter server")
return servers[0]['token']
def load_dataset(name):
token = get_jupyter_token()
# In‑cluster DNS: masking-service.default.svc.cluster.local
resp = requests.get(
f"http://masking-service.default.svc.cluster.local/datasets/{name}",
headers={"Authorization": f"Bearer {token}"}
)
resp.raise_for_status()
data = resp.json()
url = data["url"]
# Download masked data (could use pandas directly with URL)
if data["format"] == "parquet":
df = pd.read_parquet(url)
else:
df = pd.read_csv(url)
return df
scrape_configs:
- job_name: 'jupyterhub'
static_configs:
- targets: ['hub-service:8081'] # JupyterHub metrics endpoint
(Not full schema – but concept)
{
"dashboard": {
"title": "User Quota Utilization",
"panels": [
{
"type": "stat",
"title": "CPU Usage / Limit",
"targets": [{
"expr": "sum(rate(container_cpu_usage_seconds_total{namespace=~\"user-.*\"}[5m])) by (namespace)",
"legendFormat": "{{namespace}}"
}]
}
]
}
}
| Challenge | Mitigation |
|---|---|
| Data leakage – raw data exposed | Raw bucket inaccessible from user pods; only masking service has IAM role. Masked data stored in separate bucket with read‑only service account. |
Quota circumvention – low requests but high limits → noisy neighbor | Set requests == limits for strict enforcement (simpler) or deploy a custom scheduler/priority class that limits based on actual usage. Use cgroup‑based throttling. |
| GPU overcommit | Enforce limits.nvidia.com/gpu = requests via LimitRange; only whole GPU per pod. |
| Dataset discovery & policy changes | Central catalog DB; when masking rules change, re‑mask on next request (idempotent). |
| Cost visibility | Integrate kubecost or custom script to allocate node‑hour costs to user namespaces. |
| Long‑running jobs | activeDeadlineSeconds caps lifetime; batch jobs submitted via separate job queue (e.g., Argo Workflows) with TTL. |
| User experience | Pre‑install sandbox_data and MLflow; provide JupyterLab extensions showing quota usage and dataset catalog. |
| Compliance audit | Immutable log archive (S3 with object lock); capture all API calls to masking service and JupyterHub events. |
The proposed architecture delivers a secure, scalable, and fully auditable ML sandbox for external researchers. By leveraging Kubernetes for isolation and quota enforcement, a dedicated masking service for privacy, and a modern monitoring stack, the organization can open its data safely while controlling compute costs. All components are based on battle‑tested open‑source tools, making the solution practical to implement and extend.