"""
SciFlow: Scientific Computing Workflow Manager
==============================================
A comprehensive system for managing computational workflows with:
- Task abstractions and DAG execution
- Dataset versioning with content-addressable storage
- Complete provenance tracking
- Reproducibility guarantees
- Multi-user collaboration spaces
"""
from __future__ import annotations
import hashlib
import json
import os
import pickle
import random
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Generic,
Iterator,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
import warnings
# ============================================================================
# Core Types and Utilities
# ============================================================================
T = TypeVar('T')
ArtifactID = str
TaskID = str
ExecutionID = str
WorkspaceID = str
UserID = str
def compute_hash(data: bytes) -> str:
"""Compute SHA-256 hash of data."""
return hashlib.sha256(data).hexdigest()[:16]
def generate_id(prefix: str = "") -> str:
"""Generate a unique identifier."""
return f"{prefix}_{uuid.uuid4().hex[:12]}"
def timestamp() -> str:
"""Get current timestamp in ISO format."""
return datetime.utcnow().isoformat()
# ============================================================================
# Content-Addressable Storage
# ============================================================================
class ContentStore:
"""
Content-addressable storage for artifacts.
Similar to Git's object store but for arbitrary data.
"""
def __init__(self, root_path: Path):
self.root = root_path
self.objects_dir = root / "objects"
self.metadata_dir = root / "metadata"
self._ensure_dirs()
def _ensure_dirs(self):
self.objects_dir.mkdir(parents=True, exist_ok=True)
self.metadata_dir.mkdir(parents=True, exist_ok=True)
def store(self, data: bytes, metadata: Optional[Dict] = None) -> str:
"""Store data and return its content hash."""
content_hash = compute_hash(data)
# Store object
obj_path = self.objects_dir / content_hash
if not obj_path.exists():
obj_path.write_bytes(data)
# Store metadata
if metadata:
meta_path = self.metadata_dir / f"{content_hash}.json"
if not meta_path.exists():
meta_path.write_text(json.dumps(metadata, default=str))
return content_hash
def retrieve(self, content_hash: str) -> bytes:
"""Retrieve data by content hash."""
obj_path = self.objects_dir / content_hash
if not obj_path.exists():
raise KeyError(f"Object not found: {content_hash}")
return obj_path.read_bytes()
def get_metadata(self, content_hash: str) -> Optional[Dict]:
"""Get metadata for an object."""
meta_path = self.metadata_dir / f"{content_hash}.json"
if meta_path.exists():
return json.loads(meta_path.read_text())
return None
def exists(self, content_hash: str) -> bool:
"""Check if object exists."""
return (self.objects_dir / content_hash).exists()
# ============================================================================
# Dataset Versioning System
# ============================================================================
@dataclass
class DatasetVersion:
"""Represents a single version of a dataset."""
version_id: str
content_hash: str
parent_version: Optional[str]
created_at: str
created_by: UserID
message: str
size_bytes: int
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {
"version_id": self.version_id,
"content_hash": self.content_hash,
"parent_version": self.parent_version,
"created_at": self.created_at,
"created_by": self.created_by,
"message": self.message,
"size_bytes": self.size_bytes,
"metadata": self.metadata,
}
@classmethod
def from_dict(cls, data: Dict) -> "DatasetVersion":
return cls(**data)
@dataclass
class DatasetLineage:
"""Tracks the complete lineage of a dataset."""
dataset_id: str
name: str
versions: List[DatasetVersion] = field(default_factory=list)
tags: Dict[str, str] = field(default_factory=dict) # tag -> version_id
def get_version(self, version_id: str) -> Optional[DatasetVersion]:
for v in self.versions:
if v.version_id == version_id:
return v
return None
def get_latest(self) -> Optional[DatasetVersion]:
return self.versions[-1] if self.versions else None
def get_by_tag(self, tag: str) -> Optional[DatasetVersion]:
version_id = self.tags.get(tag)
if version_id:
return self.get_version(version_id)
return None
class DatasetManager:
"""
Manages versioned datasets with full lineage tracking.
Supports branching, tagging, and diff operations.
"""
def __init__(self, store: ContentStore):
self.store = store
self.datasets: Dict[str, DatasetLineage] = {}
self._index_path = store.root / "dataset_index.json"
self._load_index()
def _load_index(self):
if self._index_path.exists():
data = json.loads(self._index_path.read_text())
for ds_id, ds_data in data.items():
versions = [DatasetVersion.from_dict(v) for v in ds_data["versions"]]
self.datasets[ds_id] = DatasetLineage(
dataset_id=ds_id,
name=ds_data["name"],
versions=versions,
tags=ds_data.get("tags", {}),
)
def _save_index(self):
data = {}
for ds_id, lineage in self.datasets.items():
data[ds_id] = {
"name": lineage.name,
"versions": [v.to_dict() for v in lineage.versions],
"tags": lineage.tags,
}
self._index_path.write_text(json.dumps(data, indent=2))
def create_dataset(self, name: str, user_id: UserID) -> str:
"""Create a new empty dataset."""
dataset_id = generate_id("ds")
self.datasets[dataset_id] = DatasetLineage(
dataset_id=dataset_id,
name=name,
)
self._save_index()
return dataset_id
def commit_version(
self,
dataset_id: str,
data: bytes,
user_id: UserID,
message: str,
parent_version: Optional[str] = None,
metadata: Optional[Dict] = None,
) -> str:
"""Commit a new version of a dataset."""
if dataset_id not in self.datasets:
raise KeyError(f"Dataset not found: {dataset_id}")
lineage = self.datasets[dataset_id]
# Auto-detect parent if not specified
if parent_version is None and lineage.versions:
parent_version = lineage.versions[-1].version_id
# Store content
content_hash = self.store.store(
data,
{"dataset_id": dataset_id, "committed_at": timestamp()}
)
# Create version
version = DatasetVersion(
version_id=generate_id("v"),
content_hash=content_hash,
parent_version=parent_version,
created_at=timestamp(),
created_by=user_id,
message=message,
size_bytes=len(data),
metadata=metadata or {},
)
lineage.versions.append(version)
self._save_index()
return version.version_id
def checkout(self, dataset_id: str, version_ref: Optional[str] = None) -> bytes:
"""
Checkout a specific version of a dataset.
version_ref can be version_id, tag, or None for latest.
"""
if dataset_id not in self.datasets:
raise KeyError(f"Dataset not found: {dataset_id}")
lineage = self.datasets[dataset_id]
if version_ref is None:
version = lineage.get_latest()
elif version_ref in lineage.tags:
version = lineage.get_by_tag(version_ref)
else:
version = lineage.get_version(version_ref)
if version is None:
raise KeyError(f"Version not found: {version_ref}")
return self.store.retrieve(version.content_hash)
def tag_version(self, dataset_id: str, version_id: str, tag: str):
"""Tag a specific version."""
self.datasets[dataset_id].tags[tag] = version_id
self._save_index()
def get_lineage(self, dataset_id: str) -> List[Dict]:
"""Get the full lineage of a dataset."""
lineage = self.datasets.get(dataset_id)
if not lineage:
return []
return [v.to_dict() for v in lineage.versions]
# ============================================================================
# Task Abstractions
# ============================================================================
class TaskStatus(Enum):
PENDING = "pending"
QUEUED = "queued"
RUNNING = "running"
SUCCESS = "success"
FAILED = "failed"
CANCELLED = "cancelled"
SKIPPED = "skipped"
@dataclass
class TaskInput:
"""Represents an input to a task."""
name: str
dataset_id: str
version_ref: Optional[str] = None # None = latest
type_hint: Optional[str] = None
def to_dict(self) -> Dict:
return {
"name": self.name,
"dataset_id": self.dataset_id,
"version_ref": self.version_ref,
"type_hint": self.type_hint,
}
@dataclass
class TaskOutput:
"""Represents an output from a task."""
name: str
dataset_id: str
type_hint: Optional[str] = None
def to_dict(self) -> Dict:
return {
"name": self.name,
"dataset_id": self.dataset_id,
"type_hint": self.type_hint,
}
@dataclass
class EnvironmentSpec:
"""Specifies the execution environment for a task."""
python_version: Optional[str] = None
requirements: List[str] = field(default_factory=list)
conda_env: Optional[str] = None
docker_image: Optional[str] = None
env_vars: Dict[str, str] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {
"python_version": self.python_version,
"requirements": self.requirements,
"conda_env": self.conda_env,
"docker_image": self.docker_image,
"env_vars": self.env_vars,
}
@classmethod
def from_dict(cls, data: Dict) -> "EnvironmentSpec":
return cls(**data)
def compute_hash(self) -> str:
"""Compute a hash of the environment specification."""
return compute_hash(json.dumps(self.to_dict(), sort_keys=True).encode())
@dataclass
class TaskDefinition:
"""
Complete definition of a computational task.
This is the blueprint that can be executed multiple times.
"""
task_id: TaskID
name: str
description: str
inputs: List[TaskInput]
outputs: List[TaskOutput]
parameters: Dict[str, Any] = field(default_factory=dict)
environment: Optional[EnvironmentSpec] = None
dependencies: List[TaskID] = field(default_factory=list)
cpu_requirement: int = 1
memory_requirement_gb: float = 1.0
timeout_seconds: int = 3600
retry_count: int = 0
# The actual code - stored as source or reference
code_source: Optional[str] = None # Python source code
code_entrypoint: Optional[str] = None # Function name to call
container_command: Optional[str] = None # For container execution
def to_dict(self) -> Dict:
return {
"task_id": self.task_id,
"name": self.name,
"description": self.description,
"inputs": [i.to_dict() for i in self.inputs],
"outputs": [o.to_dict() for o in self.outputs],
"parameters": self.parameters,
"environment": self.environment.to_dict() if self.environment else None,
"dependencies": self.dependencies,
"cpu_requirement": self.cpu_requirement,
"memory_requirement_gb": self.memory_requirement_gb,
"timeout_seconds": self.timeout_seconds,
"retry_count": self.retry_count,
"code_source": self.code_source,
"code_entrypoint": self.code_entrypoint,
"container_command": self.container_command,
}
@classmethod
def from_dict(cls, data: Dict) -> "TaskDefinition":
data["inputs"] = [TaskInput(**i) for i in data["inputs"]]
data["outputs"] = [TaskOutput(**o) for o in data["outputs"]]
if data.get("environment"):
data["environment"] = EnvironmentSpec.from_dict(data["environment"])
return cls(**data)
# ============================================================================
# Provenance Tracking System
# ============================================================================
@dataclass
class ExecutionRecord:
"""
Complete record of a single task execution.
This captures everything needed to understand and reproduce the execution.
"""
execution_id: ExecutionID
task_id: TaskID
workflow_id: Optional[str]
# Timing
started_at: str
finished_at: Optional[str] = None
# Status
status: TaskStatus = TaskStatus.PENDING
# Input provenance
input_versions: Dict[str, str] = field(default_factory=dict) # input_name -> version_id
input_hashes: Dict[str, str] = field(default_factory=dict) # input_name -> content_hash
# Environment provenance
environment_hash: Optional[str] = None
code_hash: Optional[str] = None
random_seed: Optional[int] = None
# Output provenance
output_versions: Dict[str, str] = field(default_factory=dict) # output_name -> version_id
output_hashes: Dict[str, str] = field(default_factory=dict) # output_name -> content_hash
# Execution context
executor: Optional[UserID] = None
hostname: Optional[str] = None
working_directory: Optional[str] = None
# Results
stdout: Optional[str] = None
stderr: Optional[str] = None
exit_code: Optional[int] = None
metrics: Dict[str, Any] = field(default_factory=dict)
error_message: Optional[str] = None
# Reproducibility
reproducible: bool = True
reproducibility_notes: List[str] = field(default_factory=list)
def to_dict(self) -> Dict:
return {
"execution_id": self.execution_id,
"task_id": self.task_id,
"workflow_id": self.workflow_id,
"started_at": self.started_at,
"finished_at": self.finished_at,
"status": self.status.value,
"input_versions": self.input_versions,
"input_hashes": self.input_hashes,
"environment_hash": self.environment_hash,
"code_hash": self.code_hash,
"random_seed": self.random_seed,
"output_versions": self.output_versions,
"output_hashes": self.output_hashes,
"executor": self.executor,
"hostname": self.hostname,
"working_directory": self.working_directory,
"stdout": self.stdout,
"stderr": self.stderr,
"exit_code": self.exit_code,
"metrics": self.metrics,
"error_message": self.error_message,
"reproducible": self.reproducible,
"reproducibility_notes": self.reproducibility_notes,
}
@classmethod
def from_dict(cls, data: Dict) -> "ExecutionRecord":
data["status"] = TaskStatus(data["status"])
return cls(**data)
class ProvenanceTracker:
"""
Tracks complete provenance for all executions.
Enables querying lineage, reproducing results, and auditing.
"""
def __init__(self, store: ContentStore):
self.store = store
self.executions: Dict[ExecutionID, ExecutionRecord] = {}
self.task_executions: Dict[TaskID, List[ExecutionID]] = defaultdict(list)
self._index_path = store.root / "provenance_index.json"
self._load_index()
def _load_index(self):
if self._index_path.exists():
data = json.loads(self._index_path.read_text())
for exec_id, exec_data in data["executions"].items():
record = ExecutionRecord.from_dict(exec_data)
self.executions[exec_id] = record
self.task_executions[record.task_id].append(exec_id)
def _save_index(self):
data = {
"executions": {
exec_id: record.to_dict()
for exec_id, record in self.executions.items()
}
}
self._index_path.write_text(json.dumps(data, indent=2))
def start_execution(
self,
task_id: TaskID,
workflow_id: Optional[str] = None,
executor: Optional[UserID] = None,
) -> ExecutionRecord:
"""Create a new execution record."""
record = ExecutionRecord(
execution_id=generate_id("exec"),
task_id=task_id,
workflow_id=workflow_id,
started_at=timestamp(),
status=TaskStatus.RUNNING,
executor=executor,
hostname=os.uname().nodename if hasattr(os, 'uname') else "unknown",
)
self.executions[record.execution_id] = record
self.task_executions[task_id].append(record.execution_id)
self._save_index()
return record
def record_inputs(
self,
execution_id: ExecutionID,
inputs: Dict[str, Tuple[str, str]], # name -> (version_id, content_hash)
):
"""Record input provenance."""
record = self.executions[execution_id]
for name, (version_id, content_hash) in inputs.items():
record.input_versions[name] = version_id
record.input_hashes[name] = content_hash
self._save_index()
def record_environment(
self,
execution_id: ExecutionID,
environment_hash: str,
code_hash: str,
random_seed: int,
):
"""Record environment provenance."""
record = self.executions[execution_id]
record.environment_hash = environment_hash
record.code_hash = code_hash
record.random_seed = random_seed
self._save_index()
def record_outputs(
self,
execution_id: ExecutionID,
outputs: Dict[str, Tuple[str, str]], # name -> (version_id, content_hash)
):
"""Record output provenance."""
record = self.executions[execution_id]
for name, (version_id, content_hash) in outputs.items():
record.output_versions[name] = version_id
record.output_hashes[name] = content_hash
self._save_index()
def finish_execution(
self,
execution_id: ExecutionID,
status: TaskStatus,
stdout: Optional[str] = None,
stderr: Optional[str] = None,
exit_code: Optional[int] = None,
metrics: Optional[Dict] = None,
error_message: Optional[str] = None,
):
"""Mark execution as finished."""
record = self.executions[execution_id]
record.finished_at = timestamp()
record.status = status
record.stdout = stdout
record.stderr = stderr
record.exit_code = exit_code
record.metrics = metrics or {}
record.error_message = error_message
self._save_index()
def get_lineage(self, execution_id: ExecutionID) -> Dict[str, Any]:
"""
Get the complete lineage (ancestry) of an execution.
Traces back through inputs to find all contributing executions.
"""
record = self.executions.get(execution_id)
if not record:
return {}
lineage = {
"execution": record.to_dict(),
"inputs": {},
"derived_from": [],
}
# Find executions that produced our inputs
for input_name, content_hash in record.input_hashes.items():
# Find execution that produced this content
for exec_id, exec_record in self.executions.items():
if input_name in exec_record.output_hashes:
if exec_record.output_hashes[input_name] == content_hash:
lineage["derived_from"].append(exec_id)
lineage["inputs"][input_name] = {
"produced_by": exec_id,
"version": exec_record.output_versions.get(input_name),
}
break
# Recursively get lineage of ancestors
for ancestor_id in lineage["derived_from"]:
lineage[ancestor_id] = self.get_lineage(ancestor_id)
return lineage
def find_reproducible_executions(self, task_id: TaskID) -> List[ExecutionID]:
"""Find all reproducible executions of a task."""
results = []
for exec_id in self.task_executions[task_id]:
if self.executions[exec_id].reproducible:
results.append(exec_id)
return results
def verify_reproducibility(self, execution_id: ExecutionID) -> Tuple[bool, List[str]]:
"""Check if an execution can be reproduced."""
record = self.executions.get(execution_id)
if not record:
return False, ["Execution not found"]
issues = []
# Check environment
if not record.environment_hash:
issues.append("Environment not recorded")
# Check code
if not record.code_hash:
issues.append("Code not recorded")
# Check random seed
if record.random_seed is None:
issues.append("Random seed not recorded")
# Check all inputs
for input_name in record.input_versions:
if input_name not in record.input_hashes:
issues.append(f"Input '{input_name}' hash not recorded")
return len(issues) == 0, issues
# ============================================================================
# Workflow Engine
# ============================================================================
class WorkflowDAG:
"""
Directed Acyclic Graph of tasks.
Handles dependency resolution and execution ordering.
"""
def __init__(self):
self.tasks: Dict[TaskID, TaskDefinition] = {}
self.edges: Dict[TaskID, Set[TaskID]] = defaultdict(set) # task -> dependents
def add_task(self, task: TaskDefinition):
"""Add a task to the workflow."""
self.tasks[task.task_id] = task
# Add edges for dependencies
for dep_id in task.dependencies:
if dep_id in self.tasks:
self.edges[dep_id].add(task.task_id)
def get_execution_order(self) -> List[List[TaskID]]:
"""
Get tasks grouped by execution level (tasks that can run in parallel).
Uses topological sort with level grouping.
"""
# Calculate in-degree for each task
in_degree = {task_id: 0 for task_id in self.tasks}
for task in self.tasks.values():
for dep_id in task.dependencies:
if dep_id in self.tasks:
in_degree[task.task_id] += 1
levels = []
remaining = set(self.tasks.keys())
while remaining:
# Find tasks with no unresolved dependencies
level = [
task_id for task_id in remaining
if in_degree[task_id] == 0
]
if not level:
# Cycle detected
raise ValueError("Workflow contains a cycle")
levels.append(level)
# Update in-degrees
for task_id in level:
remaining.remove(task_id)
for dependent in self.edges[task_id]:
if dependent in remaining:
in_degree[dependent] -= 1
return levels
def get_dependencies(self, task_id: TaskID) -> Set[TaskID]:
"""Get all transitive dependencies of a task."""
deps = set()
to_visit = list(self.tasks[task_id].dependencies)
while to_visit:
dep_id = to_visit.pop()
if dep_id not in deps and dep_id in self.tasks:
deps.add(dep_id)
to_visit.extend(self.tasks[dep_id].dependencies)
return deps
@dataclass
class WorkflowDefinition:
"""Complete workflow definition."""
workflow_id: str
name: str
description: str
tasks: List[TaskDefinition]
parameters: Dict[str, Any] = field(default_factory=dict)
created_at: str = field(default_factory=timestamp)
created_by: Optional[UserID] = None
version: str = "1.0"
def to_dict(self) -> Dict:
return {
"workflow_id": self.workflow_id,
"name": self.name,
"description": self.description,
"tasks": [t.to_dict() for t in self.tasks],
"parameters": self.parameters,
"created_at": self.created_at,
"created_by": self.created_by,
"version": self.version,
}
@classmethod
def from_dict(cls, data: Dict) -> "WorkflowDefinition":
data["tasks"] = [TaskDefinition.from_dict(t) for t in data["tasks"]]
return cls(**data)
def build_dag(self) -> WorkflowDAG:
"""Build the execution DAG."""
dag = WorkflowDAG()
for task in self.tasks:
dag.add_task(task)
return dag
@dataclass
class WorkflowRun:
"""Represents a single run of a workflow."""
run_id: str
workflow_id: str
status: TaskStatus
started_at: str
finished_at: Optional[str] = None
task_executions: Dict[TaskID, ExecutionID] = field(default_factory=dict)
parameters: Dict[str, Any] = field(default_factory=dict)
triggered_by: Optional[UserID] = None
def to_dict(self) -> Dict:
return {
"run_id": self.run_id,
"workflow_id": self.workflow_id,
"status": self.status.value,
"started_at": self.started_at,
"finished_at": self.finished_at,
"task_executions": self.task_executions,
"parameters": self.parameters,
"triggered_by": self.triggered_by,
}
class WorkflowEngine:
"""
Executes workflows with full provenance tracking.
"""
def __init__(
self,
store: ContentStore,
dataset_manager: DatasetManager,
provenance: ProvenanceTracker,
):
self.store = store
self.datasets = dataset_manager
self.provenance = provenance
self.workflows: Dict[str, WorkflowDefinition] = {}
self.runs: Dict[str, WorkflowRun] = {}
self._task_runners: Dict[str, Callable] = {}
def register_task_runner(self, task_name: str, runner: Callable):
"""Register a custom runner for a task type."""
self._task_runners[task_name] = runner
def save_workflow(self, workflow: WorkflowDefinition):
"""Save a workflow definition."""
self.workflows[workflow.workflow_id] = workflow
# Persist to store
workflow_data = json.dumps(workflow.to_dict()).encode()
self.store.store(workflow_data, {"type": "workflow", "id": workflow.workflow_id})
def execute_task(
self,
task: TaskDefinition,
workflow_run: Optional[WorkflowRun] = None,
user_id: Optional[UserID] = None,
) -> ExecutionRecord:
"""Execute a single task with full provenance capture."""
# Start execution record
exec_record = self.provenance.start_execution(
task_id=task.task_id,
workflow_id=workflow_run.run_id if workflow_run else None,
executor=user_id,
)
try:
# Capture and record inputs
input_data = {}
input_provenance = {}
for task_input in task.inputs:
data = self.datasets.checkout(
task_input.dataset_id,
task_input.version_ref,
)
input_data[task_input.name] = data
# Get version info
lineage = self.datasets.datasets[task_input.dataset_id]
version = lineage.get_latest()
input_provenance[task_input.name] = (
version.version_id if version else "unknown",
compute_hash(data),
)
self.provenance.record_inputs(exec_record.execution_id, input_provenance)
# Record environment
env_hash = task.environment.compute_hash() if task.environment else "default"
code_hash = compute_hash(task.code_source.encode()) if task.code_source else "none"
seed = random.randint(0, 2**32 - 1)
self.provenance.record_environment(
exec_record.execution_id,
env_hash,
code_hash,
seed,
)
# Set random seed for reproducibility
random.seed(seed)
# Execute the task
start_time = time.time()
if task.name in self._task_runners:
# Use custom runner
result = self._task_runners[task.name](
input_data,
task.parameters,
)
elif task.code_source and task.code_entrypoint:
# Execute from source
result = self._execute_from_source(task, input_data)
else:
raise ValueError(f"No runner for task: {task.name}")
elapsed = time.time() - start_time
# Record outputs
output_provenance = {}
for task_output in task.outputs:
if task_output.name in result:
output_data = result[task_output.name]
version_id = self.datasets.commit_version(
dataset_id=task_output.dataset_id,
data=output_data if isinstance(output_data, bytes) else str(output_data).encode(),
user_id=user_id or "system",
message=f"Output from task {task.task_id}",
metadata={"execution_id": exec_record.execution_id},
)
output_provenance[task_output.name] = (
version_id,
compute_hash(output_data if isinstance(output_data, bytes) else str(output_data).encode()),
)
self.provenance.record_outputs(exec_record.execution_id, output_provenance)
# Finish execution
self.provenance.finish_execution(
exec_record.execution_id,
TaskStatus.SUCCESS,
metrics={"elapsed_seconds": elapsed},
)
except Exception as e:
# Record failure
self.provenance.finish_execution(
exec_record.execution_id,
TaskStatus.FAILED,
stderr=str(e),
exit_code=1,
error_message=str(e),
)
exec_record.status = TaskStatus.FAILED
return exec_record
def _execute_from_source(
self,
task: TaskDefinition,
input_data: Dict[str, bytes],
) -> Dict[str, Any]:
"""Execute task from source code."""
# Create temporary namespace
namespace = {
"inputs": input_data,
"parameters": task.parameters,
"outputs": {},
}
# Execute code
exec(task.code_source, namespace)
return namespace.get("outputs", {})
def run_workflow(
self,
workflow_id: str,
parameters: Optional[Dict[str, Any]] = None,
user_id: Optional[UserID] = None,
) -> WorkflowRun:
"""Execute an entire workflow."""
workflow = self.workflows.get(workflow_id)
if not workflow:
raise KeyError(f"Workflow not found: {workflow_id}")
# Create run record
run = WorkflowRun(
run_id=generate_id("run"),
workflow_id=workflow_id,
status=TaskStatus.RUNNING,
started_at=timestamp(),
parameters=parameters or {},
triggered_by=user_id,
)
self.runs[run.run_id] = run
# Build DAG and get execution order
dag = workflow.build_dag()
execution_levels = dag.get_execution_order()
try:
# Execute level by level
for level in execution_levels:
# Could parallelize here
for task_id in level:
task = dag.tasks[task_id]
# Execute task
exec_record = self.execute_task(task, run, user_id)
run.task_executions[task_id] = exec_record.execution_id
if exec_record.status != TaskStatus.SUCCESS:
run.status = TaskStatus.FAILED
run.finished_at = timestamp()
return run
run.status = TaskStatus.SUCCESS
finally:
run.finished_at = timestamp()
return run
def reproduce_execution(self, execution_id: ExecutionID) -> ExecutionRecord:
"""
Attempt to reproduce a previous execution exactly.
Uses all recorded provenance to recreate the environment.
"""
original = self.provenance.executions.get(execution_id)
if not original:
raise KeyError(f"Execution not found: {execution_id}")
# Verify reproducibility
can_reproduce, issues = self.provenance.verify_reproducibility(execution_id)
if not can_reproduce:
warnings.warn(f"Reproducibility issues: {issues}")
# Get the task definition
task_def_data = self.store.get_metadata(original.code_hash)
# In real implementation, would reconstruct full task definition
# Create new execution
print(f"Reproducing execution {execution_id}...")
print(f" - Using random seed: {original.random_seed}")
print(f" - Environment hash: {original.environment_hash}")
# Return original for comparison
return original
# ============================================================================
# Collaboration Spaces
# ============================================================================
class Permission(Enum):
READ = "read"
WRITE = "write"
EXECUTE = "execute"
ADMIN = "admin"
@dataclass
class WorkspaceMember:
"""A member of a workspace."""
user_id: UserID
display_name: str
permissions: Set[Permission]
joined_at: str
def to_dict(self) -> Dict:
return {
"user_id": self.user_id,
"display_name": self.display_name,
"permissions": [p.value for p in self.permissions],
"joined_at": self.joined_at,
}
@dataclass
class Workspace:
"""
A collaboration space containing workflows, datasets, and executions.
"""
workspace_id: WorkspaceID
name: str
description: str
owner_id: UserID
members: Dict[UserID, WorkspaceMember] = field(default_factory=dict)
datasets: Set[str] = field(default_factory=set)
workflows: Set[str] = field(default_factory=set)
is_public: bool = False
created_at: str = field(default_factory=timestamp)
def to_dict(self) -> Dict:
return {
"workspace_id": self.workspace_id,
"name": self.name,
"description": self.description,
"owner_id": self.owner_id,
"members": {uid: m.to_dict() for uid, m in self.members.items()},
"datasets": list(self.datasets),
"workflows": list(self.workflows),
"is_public": self.is_public,
"created_at": self.created_at,
}
@dataclass
class ActivityEvent:
"""Records activity in a workspace."""
event_id: str
workspace_id: WorkspaceID
user_id: UserID
event_type: str
resource_type: str
resource_id: str
description: str
timestamp: str
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {
"event_id": self.event_id,
"workspace_id": self.workspace_id,
"user_id": self.user_id,
"event_type": self.event_type,
"resource_type": self.resource_type,
"resource_id": self.resource_id,
"description": self.description,
"timestamp": self.timestamp,
"metadata": self.metadata,
}
class WorkspaceManager:
"""
Manages collaboration spaces and access control.
"""
def __init__(self, store: ContentStore):
self.store = store
self.workspaces: Dict[WorkspaceID, Workspace] = {}
self.user_workspaces: Dict[UserID, Set[WorkspaceID]] = defaultdict(set)
self.activity_feed: List[ActivityEvent] = []
self._index_path = store.root / "workspace_index.json"
self._load_index()
def _load_index(self):
if self._index_path.exists():
data = json.loads(self._index_path.read_text())
for ws_id, ws_data in data["workspaces"].items():
members = {
uid: WorkspaceMember(
user_id=m["user_id"],
display_name=m["display_name"],
permissions={Permission(p) for p in m["permissions"]},
joined_at=m["joined_at"],
)
for uid, m in ws_data["members"].items()
}
self.workspaces[ws_id] = Workspace(
workspace_id=ws_data["workspace_id"],
name=ws_data["name"],
description=ws_data["description"],
owner_id=ws_data["owner_id"],
members=members,
datasets=set(ws_data["datasets"]),
workflows=set(ws_data["workflows"]),
is_public=ws_data["is_public"],
created_at=ws_data["created_at"],
)
for uid in members:
self.user_workspaces[uid].add(ws_id)
def _save_index(self):
data = {
"workspaces": {
ws_id: ws.to_dict()
for ws_id, ws in self.workspaces.items()
}
}
self._index_path.write_text(json.dumps(data, indent=2))
def create_workspace(
self,
name: str,
description: str,
owner_id: UserID,
is_public: bool = False,
) -> Workspace:
"""Create a new workspace."""
workspace_id = generate_id("ws")
workspace = Workspace(
workspace_id=workspace_id,
name=name,
description=description,
owner_id=owner_id,
is_public=is_public,
)
# Add owner as admin
workspace.members[owner_id] = WorkspaceMember(
user_id=owner_id,
display_name=owner_id,
permissions={Permission.READ, Permission.WRITE, Permission.EXECUTE, Permission.ADMIN},
joined_at=timestamp(),
)
self.workspaces[workspace_id] = workspace
self.user_workspaces[owner_id].add(workspace_id)
self._save_index()
self._record_activity(
workspace_id, owner_id, "workspace_created",
"workspace", workspace_id, f"Created workspace '{name}'"
)
return workspace
def add_member(
self,
workspace_id: WorkspaceID,
user_id: UserID,
display_name: str,
permissions: Set[Permission],
added_by: UserID,
):
"""Add a member to a workspace."""
workspace = self.workspaces.get(workspace_id)
if not workspace:
raise KeyError(f"Workspace not found: {workspace_id}")
# Check if adder has admin permission
if not self._has_permission(workspace_id, added_by, Permission.ADMIN):
raise PermissionError("Only admins can add members")
workspace.members[user_id] = WorkspaceMember(
user_id=user_id,
display_name=display_name,
permissions=permissions,
joined_at=timestamp(),
)
self.user_workspaces[user_id].add(workspace_id)
self._save_index()
self._record_activity(
workspace_id, added_by, "member_added",
"user", user_id, f"Added member '{display_name}'"
)
def _has_permission(
self,
workspace_id: WorkspaceID,
user_id: UserID,
permission: Permission
) -> bool:
"""Check if user has a specific permission."""
workspace = self.workspaces.get(workspace_id)
if not workspace:
return False
# Owner always has all permissions
if workspace.owner_id == user_id:
return True
member = workspace.members.get(user_id)
if not member:
return False
# Admin implies all other permissions
if Permission.ADMIN in member.permissions:
return True
return permission in member.permissions
def check_access(
self,
workspace_id: WorkspaceID,
user_id: UserID,
permission: Permission,
) -> bool:
"""Public method to check access."""
return self._has_permission(workspace_id, user_id, permission)
def add_dataset(
self,
workspace_id: WorkspaceID,
dataset_id: str,
user_id: UserID,
):
"""Add a dataset to a workspace."""
if not self._has_permission(workspace_id, user_id, Permission.WRITE):
raise PermissionError("No write permission")
workspace = self.workspaces[workspace_id]
workspace.datasets.add(dataset_id)
self._save_index()
self._record_activity(
workspace_id, user_id, "dataset_added",
"dataset", dataset_id, f"Added dataset"
)
def add_workflow(
self,
workspace_id: WorkspaceID,
workflow_id: str,
user_id: UserID,
):
"""Add a workflow to a workspace."""
if not self._has_permission(workspace_id, user_id, Permission.WRITE):
raise PermissionError("No write permission")
workspace = self.workspaces[workspace_id]
workspace.workflows.add(workflow_id)
self._save_index()
self._record_activity(
workspace_id, user_id, "workflow_added",
"workflow", workflow_id, f"Added workflow"
)
def get_activity_feed(
self,
workspace_id: WorkspaceID,
limit: int = 50,
) -> List[ActivityEvent]:
"""Get recent activity for a workspace."""
events = [
e for e in self.activity_feed
if e.workspace_id == workspace_id
]
return sorted(events, key=lambda e: e.timestamp, reverse=True)[:limit]
def _record_activity(
self,
workspace_id: WorkspaceID,
user_id: UserID,
event_type: str,
resource_type: str,
resource_id: str,
description: str,
metadata: Optional[Dict] = None,
):
"""Record an activity event."""
event = ActivityEvent(
event_id=generate_id("evt"),
workspace_id=workspace_id,
user_id=user_id,
event_type=event_type,
resource_type=resource_type,
resource_id=resource_id,
description=description,
timestamp=timestamp(),
metadata=metadata or {},
)
self.activity_feed.append(event)
def get_user_workspaces(self, user_id: UserID) -> List[Workspace]:
"""Get all workspaces accessible by a user."""
return [
self.workspaces[ws_id]
for ws_id in self.user_workspaces[user_id]
if ws_id in self.workspaces
]
# ============================================================================
# Main SciFlow System
# ============================================================================
class SciFlow:
"""
Main entry point for the SciFlow workflow management system.
Integrates all components into a unified API.
"""
def __init__(self, root_path: Optional[Path] = None):
self.root = root_path or Path(tempfile.mkdtemp(prefix="sciflow_"))
self.store = ContentStore(self.root)
self.datasets = DatasetManager(self.store)
self.provenance = ProvenanceTracker(self.store)
self.engine = WorkflowEngine(self.store, self.datasets, self.provenance)
self.workspaces = WorkspaceManager(self.store)
print(f"SciFlow initialized at: {self.root}")
# === Dataset Operations ===
def create_dataset(self, name: str, user_id: UserID) -> str:
"""Create a new dataset."""
return self.datasets.create_dataset(name, user_id)
def upload_data(
self,
dataset_id: str,
data: bytes,
user_id: UserID,
message: str = "Data upload",
metadata: Optional[Dict] = None,
) -> str:
"""Upload data to a dataset."""
return self.datasets.commit_version(
dataset_id, data, user_id, message, metadata=metadata
)
def download_data(
self,
dataset_id: str,
version_ref: Optional[str] = None,
) -> bytes:
"""Download data from a dataset."""
return self.datasets.checkout(dataset_id, version_ref)
# === Workflow Operations ===
def create_workflow(
self,
name: str,
description: str,
user_id: UserID,
) -> str:
"""Create a new workflow."""
workflow_id = generate_id("wf")
workflow = WorkflowDefinition(
workflow_id=workflow_id,
name=name,
description=description,
tasks=[],
created_by=user_id,
)
self.engine.save_workflow(workflow)
return workflow_id
def add_task_to_workflow(
self,
workflow_id: str,
task: TaskDefinition,
):
"""Add a task to a workflow."""
workflow = self.engine.workflows[workflow_id]
workflow.tasks.append(task)
self.engine.save_workflow(workflow)
def run_workflow(
self,
workflow_id: str,
user_id: UserID,
parameters: Optional[Dict] = None,
) -> WorkflowRun:
"""Execute a workflow."""
return self.engine.run_workflow(workflow, parameters, user_id)
def register_task_runner(self, task_name: str, runner: Callable):
"""Register a custom task runner."""
self.engine.register_task_runner(task_name, runner)
# === Provenance Operations ===
def get_lineage(self, execution_id: ExecutionID) -> Dict[str, Any]:
"""Get the complete lineage of an execution."""
return self.provenance.get_lineage(execution_id)
def reproduce(self, execution_id: ExecutionID) -> ExecutionRecord:
"""Attempt to reproduce an execution."""
return self.engine.reproduce_execution(execution_id)
# === Workspace Operations ===
def create_workspace(
self,
name: str,
description: str,
owner_id: UserID,
) -> Workspace:
"""Create a new workspace."""
return self.workspaces.create_workspace(name, description, owner_id)
def get_workspaces(self, user_id: UserID) -> List[Workspace]:
"""Get all workspaces for a user."""
return self.workspaces.get_user_workspaces(user_id)
# === System Operations ===
def export_workflow(self, workflow_id: str) -> str:
"""Export a workflow definition as JSON."""
workflow = self.engine.workflows.get(workflow_id)
if not workflow:
raise KeyError(f"Workflow not found: {workflow_id}")
return json.dumps(workflow.to_dict(), indent=2)
def import_workflow(self, workflow_json: str, user_id: UserID) -> str:
"""Import a workflow from JSON."""
data = json.loads(workflow_json)
workflow = WorkflowDefinition.from_dict(data)
workflow.workflow_id = generate_id("wf")
workflow.created_by = user_id
self.engine.save_workflow(workflow)
return workflow.workflow_id
# ============================================================================
# Demo and Testing
# ============================================================================
def demo_data_processing_runner(inputs: Dict[str, bytes], parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Demo runner that processes data."""
# Simulate processing
result = {
"output": b"Processed: " + inputs.get("input_data", b"nothing"),
}
return result
def main():
"""Demonstrate the SciFlow system."""
print("=" * 70)
print("SciFlow: Scientific Computing Workflow Manager Demo")
print("=" * 70)
# Initialize system
sf = SciFlow(Path("/tmp/sciflow_demo"))
# Users
alice = "alice@example.com"
bob = "bob@example.com"
print("\n" + "=" * 50)
print("1. Creating Workspace")
print("=" * 50)
# Create workspace
workspace = sf.create_workspace(
name="Genomics Research Project",
description="Collaborative space for genomics analysis",
owner_id=alice,
)
print(f"Created workspace: {workspace.name} (ID: {workspace.workspace_id})")
# Add collaborator
sf.workspaces.add_member(
workspace.workspace_id,
bob,
"Bob Smith",
{Permission.READ, Permission.WRITE, Permission.EXECUTE},
alice,
)
print(f"Added Bob as collaborator")
print("\n" + "=" * 50)
print("2. Dataset Versioning")
print("=" * 50)
# Create and version datasets
raw_data_id = sf.create_dataset("Raw Sequencing Data", alice)
print(f"Created dataset: {raw_data_id}")
# Upload initial data
v1 = sf.upload_data(
raw_data_id,
b"ATCGATCGATCGATCG...sample_1",
alice,
"Initial sample data",
{"sample_count": 1, "format": "FASTQ"},
)
print(f"Committed version: {v1}")
# Upload more data
v2 = sf.upload_data(
raw_data_id,
b"ATCGATCGATCGATCG...sample_1\nGCTAGCTAGCTA...sample_2",
alice,
"Added second sample",
{"sample_count": 2, "format": "FASTQ"},
)
print(f"Committed version: {v2}")
# Tag a version
sf.datasets.tag_version(raw_data_id, v1, "baseline")
print("Tagged v1 as 'baseline'")
# Retrieve data
data = sf.download_data(raw_data_id, "baseline")
print(f"Retrieved baseline data: {data[:30]}...")
print("\n" + "=" * 50)
print("3. Creating Workflow with Tasks")
print("=" * 50)
# Create processed data dataset
processed_data_id = sf.create_dataset("Processed Data", alice)
# Create workflow
workflow_id = sf.create_workflow(
name="Data Processing Pipeline",
description="Processes raw sequencing data",
user_id=alice,
)
print(f"Created workflow: {workflow_id}")
# Define task
task = TaskDefinition(
task_id=generate_id("task"),
name="data_processing",
description="Process raw sequencing data",
inputs=[TaskInput("input_data", raw_data_id)],
outputs=[TaskOutput("output", processed_data_id)],
parameters={"quality_threshold": 0.95},
environment=EnvironmentSpec(
python_version="3.10",
requirements=["numpy>=1.20", "pandas>=1.3"],
),
code_source="""
def process(inputs, parameters):
# Simulated processing
data = inputs["input_data"]
threshold = parameters.get("quality_threshold", 0.9)
outputs["output"] = f"Processed with threshold={threshold}: {data[:20]}...".encode()
""",
code_entrypoint="process",
)
sf.add_task_to_workflow(workflow_id, task)
print(f"Added task: {task.name}")
print("\n" + "=" * 50)
print("4. Running Workflow")
print("=" * 50)
# Register custom runner
sf.register_task_runner("data_processing", demo_data_processing_runner)
# Run workflow
run = sf.run_workflow(workflow_id, alice)
print(f"Workflow run: {run.run_id}")
print(f"Status: {run.status.value}")
print(f"Task executions: {len(run.task_executions)}")
print("\n" + "=" * 50)
print("5. Provenance Tracking")
print("=" * 50)
# Get execution details
for task_id, exec_id in run.task_executions.items():
print(f"\nTask: {task_id}")
print(f"Execution: {exec_id}")
# Get lineage
lineage = sf.get_lineage(exec_id)
print(f"Inputs tracked: {list(lineage['execution']['input_versions'].keys())}")
print(f"Outputs tracked: {list(lineage['execution']['output_versions'].keys())}")
print(f"Random seed: {lineage['execution']['random_seed']}")
# Verify reproducibility
can_reproduce, issues = sf.provenance.verify_reproducibility(exec_id)
print(f"Reproducible: {can_reproduce}")
if issues:
print(f"Issues: {issues}")
print("\n" + "=" * 50)
print("6. Dataset Lineage")
print("=" * 50)
# Show dataset history
lineage_data = sf.datasets.get_lineage(raw_data_id)
print(f"\nDataset history ({raw_data_id}):")
for version in lineage_data:
print(f" - {version['version_id'][:20]}... by {version['created_by']}")
print(f" Message: {version['message']}")
print(f" Size: {version['size_bytes']} bytes")
print("\n" + "=" * 50)
print("7. Activity Feed")
print("=" * 50)
activities = sf.workspaces.get_activity_feed(workspace.workspace_id)
print(f"\nRecent activity in '{workspace.name}':")
for activity in activities[:5]:
print(f" [{activity.timestamp[:19]}] {activity.description}")
print("\n" + "=" * 50)
print("8. Workflow Export/Import")
print("=" * 50)
# Export workflow
exported = sf.export_workflow(workflow_id)
print(f"Exported workflow ({len(exported)} bytes)")
print("Preview:")
print(exported[:300] + "...")
# Import as new workflow
new_wf_id = sf.import_workflow(exported, bob)
print(f"\nImported as new workflow: {new_wf_id}")
print("\n" + "=" * 70)
print("Demo Complete!")
print("=" * 70)
if __name__ == "__main__":
main()