dartfx-workspace

Data Artifex Workspace package.

class dartfx.workspace.AccessPolicy[source]

Bases: object

Evaluates 3-tier authorization and storage quota policies.

classmethod authorize(principal: Principal, ws_config: WorkspaceConfig, action: Action) → None[source]

Verify authorization or raise WorkspaceAccessDeniedError.

classmethod authorize_space(principal: Principal, space_config: SpaceConfig, action: Action) → None[source]

Verify space authorization or raise WorkspaceAccessDeniedError.

static can_access_space(principal: Principal, space_config: SpaceConfig, action: Action) → bool[source]

Return whether the principal is allowed to perform an action on a Space.

static can_access_workspace(principal: Principal, ws_config: WorkspaceConfig, action: Action) → bool[source]

Return whether the principal is allowed to perform an action on a Workspace.

static check_quota(current_bytes: int, additional_bytes: int, quota_bytes: int | None) → None[source]

Ensure adding additional_bytes does not exceed quota_bytes.

class dartfx.workspace.AccessTier(*values)[source]

Bases: StrEnum

Authentication/authorization tier for a caller principal.

ADMIN = 'admin'
ANONYMOUS = 'anonymous'
USER = 'user'
class dartfx.workspace.Action(*values)[source]

Bases: StrEnum

Actions guarded by AccessPolicy.

ADMIN = 'admin'
EXECUTE = 'execute'
READ = 'read'
WRITE = 'write'
class dartfx.workspace.FileEntry(*, name: str, path: str, is_dir: bool, size_bytes: int, modified_at: datetime, registered: bool, uuid: str | None = None, file_type: str = '-', file_format: str = 'undetermined', mime_type: str | None = None, is_generated: bool = False, generated_by: str | None = None, source_uuid: str | None = None, fairify_status: str | None = None, applicable_actions: list[str] = <factory>)[source]

Bases: BaseModel

Structured directory/file listing entry with Knowledge Base enrichment.

applicable_actions: list[str]
fairify_status: str | None
file_format: str
file_type: str
generated_by: str | None
is_dir: bool
is_generated: bool
mime_type: str | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

modified_at: datetime
name: str
path: str
registered: bool
size_bytes: int
source_uuid: str | None
uuid: str | None
class dartfx.workspace.FilePreview(*, path: str, mode: str, lines_requested: int, lines: list[str], total_size_bytes: int)[source]

Bases: BaseModel

Head or tail text preview of a workspace file.

lines: list[str]
lines_requested: int
mode: str
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: str
total_size_bytes: int
class dartfx.workspace.FileResource(*, id: UUID, path: Path, size_bytes: int, created_at: datetime, updated_at: datetime, blake3_hash: str, type: FileType = FileType.OTHER, file_format: FileFormat = FileFormat.UNDETERMINED, is_generated: bool = False, generated_by: str | None = None, source_uuid: str | None = None, applicable_actions: list[str] = <factory>)[source]

Bases: BaseModel

Metadata representation of a file resource in the workspace. Maintains a stable UUID that persists across renames/moves within the workspace.

applicable_actions: list[str]
blake3_hash: str
created_at: datetime
file_format: FileFormat
generated_by: str | None
id: UUID
is_generated: bool
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: Path
size_bytes: int
source_uuid: str | None
type: FileType
updated_at: datetime
class dartfx.workspace.FileType(*values)[source]

Bases: StrEnum

Broad file classification category.

CODE = 'code'
COMPRESSED = 'compressed'
DATA = 'data'
DOCUMENTATION = 'documentation'
MEDIA = 'media'
METADATA = 'metadata'
OTHER = 'other'
class dartfx.workspace.FileTypeStats(*, count: int = 0, size_bytes: int = 0)[source]

Bases: BaseModel

count: int
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

size_bytes: int
class dartfx.workspace.IngestionPolicy(*, enforce_zones: bool = True, max_upload_size_bytes: int | None = None, zones: list[ZoneRule] = <factory>)[source]

Bases: BaseModel

Configuration for file upload, import, and path-based zone restrictions.

enforce_zones: bool
max_upload_size_bytes: int | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

zones: list[ZoneRule]
exception dartfx.workspace.IngestionPolicyViolationError[source]

Bases: PolicyViolationError

Raised when file upload, import, or placement violates a workspace zone or ingestion policy.

class dartfx.workspace.PolicyEvaluator[source]

Bases: object

Evaluates workspace rename and ingestion/zone policies.

classmethod evaluate_ingestion(settings: WorkspaceSettings, filename_or_path: Path | str, dest_rel_path: str, *, content_path: Path | None = None, size_bytes: int | None = None, is_generated: bool | None = None, allow_override: bool = False) → None[source]

Validate a file upload/placement against IngestionPolicy and matching ZoneRule.

classmethod evaluate_rename(settings: WorkspaceSettings, src: Path, dst: Path, *, workspace_root: Path | None = None, allow_override: bool = False) → None[source]

Validate a file rename/move against the workspace RenamePolicy and target ZoneRule.

static find_matching_zone(rel_path: str, rules: list[ZoneRule]) → ZoneRule | None[source]

Return the first ZoneRule matching the workspace-relative path, if any.

exception dartfx.workspace.PolicyViolationError[source]

Bases: ValueError

Base exception raised when an operation violates a configured workspace policy.

class dartfx.workspace.Principal(*, id: str = 'anonymous', tier: AccessTier = AccessTier.ANONYMOUS, label: str = 'Anonymous', team_ids: list[str] = <factory>, allowed_space_ids: list[str] = <factory>)[source]

Bases: BaseModel

Identity and authorization context for programmatic or API callers.

allowed_space_ids: list[str]
id: str
label: str
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

team_ids: list[str]
tier: AccessTier
exception dartfx.workspace.QuotaExceededError[source]

Bases: ValueError

Raised when an operation would exceed a workspace or space storage quota.

class dartfx.workspace.RenameMode(*values)[source]

Bases: StrEnum

Policy mode controlling file extension/format changes during rename/move.

PERMISSIVE = 'permissive'
SAME_FORMAT = 'same_format'
SAME_TYPE = 'same_type'
STRICT = 'strict'
class dartfx.workspace.RenamePolicy(*, mode: RenameMode = RenameMode.SAME_FORMAT, allow_sidecar_rename: bool = False, allow_cross_zone_move: bool = True)[source]

Bases: BaseModel

Configuration for file rename and move operations.

allow_cross_zone_move: bool
allow_sidecar_rename: bool
mode: RenameMode
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

exception dartfx.workspace.RenamePolicyViolationError[source]

Bases: PolicyViolationError

Raised when a file rename or move violates the workspace rename policy.

class dartfx.workspace.ResourceDetail(*, uuid: str, path: str, size_bytes: int, blake3_hash: str, type: str, file_format: str, mime_type: str | None = None, created_at: str, updated_at: str, is_generated: bool = False, generated_by: str | None = None, source_uuid: str | None = None, fairify_status: str | None = None, applicable_actions: list[str] = <factory>, attributes: dict[str, str]=<factory>)[source]

Bases: BaseModel

Detailed Knowledge Base metadata and format-specific attributes for a file resource.

applicable_actions: list[str]
attributes: dict[str, str]
blake3_hash: str
created_at: str
fairify_status: str | None
file_format: str
generated_by: str | None
is_generated: bool
mime_type: str | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

path: str
size_bytes: int
source_uuid: str | None
type: str
updated_at: str
uuid: str
class dartfx.workspace.Space(config: SpaceConfig)[source]

Bases: object

Virtual storage area grouping workspaces and enforcing aggregate storage quotas.

check_space_quota(additional_bytes: int, current_used: int | None = None) → None[source]

Validate that adding additional_bytes does not breach the Space quota.

classmethod provision_ephemeral_workspace(path: Path, sample_files: bool = True) → Workspace[source]

Initialize an ephemeral sandbox workspace with standard folders and sample assets.

classmethod reset_ephemeral_workspace(path: Path, sample_files: bool = True) → Workspace[source]

Wipe and re-provision an ephemeral workspace from scratch.

stats(workspaces: list[Workspace]) → SpaceStats[source]

Compute aggregate SpaceStats across the given workspaces.

total_usage_bytes(workspaces: list[Workspace] | None = None) → int[source]

Compute total user-file storage used across workspaces or the space root.

class dartfx.workspace.SpaceConfig(*, id: str, slug: str, name: str, description: str = '', root_path: Path, storage_quota_bytes: int | None = None, visibility: Visibility = Visibility.PUBLIC)[source]

Bases: BaseModel

Configuration metadata for a virtual Space grouping workspaces.

description: str
id: str
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str
root_path: Path
slug: str
storage_quota_bytes: int | None
visibility: Visibility
class dartfx.workspace.SpaceStats(*, space_id: str, workspace_count: int, total_files: int, total_size_bytes: int, storage_quota_bytes: int | None = None, quota_used_pct: float | None = None)[source]

Bases: BaseModel

Aggregate usage and quota telemetry for a Space.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

quota_used_pct: float | None
space_id: str
storage_quota_bytes: int | None
total_files: int
total_size_bytes: int
workspace_count: int
class dartfx.workspace.SparqlResult(*, columns: list[str], rows: list[dict[str, str | None]], row_count: int)[source]

Bases: BaseModel

Tabular result of a read-only SPARQL query against the Knowledge Base.

columns: list[str]
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

row_count: int
rows: list[dict[str, str | None]]
class dartfx.workspace.TabularQueryResult(*, columns: list[str], rows: list[dict[str, str | int | float | bool | None]], row_count: int)[source]

Bases: BaseModel

Tabular result of an analytical SQL query against workspace data files.

columns: list[str]
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

row_count: int
rows: list[dict[str, str | int | float | bool | None]]
class dartfx.workspace.TaskEvent(*, task_id: str, workspace_id: str, task_type: TaskType, status: TaskStatus, progress_pct: float = 0.0, current_step: str = '', log_line: str | None = None, result: dict[str, str | int | float | bool | list[str] | None] | None=None, error: str | None = None, timestamp: datetime = <factory>)[source]

Bases: BaseModel

Structured event emitted during asynchronous task execution.

current_step: str
error: str | None
log_line: str | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

progress_pct: float
result: dict[str, str | int | float | bool | list[str] | None] | None
status: TaskStatus
task_id: str
task_type: TaskType
timestamp: datetime
workspace_id: str
class dartfx.workspace.TaskStatus(*values)[source]

Bases: StrEnum

Lifecycle status for asynchronous workspace tasks.

CANCELLED = 'cancelled'
COMPLETED = 'completed'
FAILED = 'failed'
PENDING = 'pending'
RUNNING = 'running'
class dartfx.workspace.TaskType(*values)[source]

Bases: StrEnum

Supported asynchronous workspace task types.

FAIRIFY = 'fairify'
READSTAT = 'readstat'
SCAN = 'scan'
TOCSV = 'tocsv'
class dartfx.workspace.TreeNode(*, name: str, path: str, is_dir: bool, registered: bool = False, uuid: str | None = None, file_type: str = '-', file_format: str = 'undetermined', is_generated: bool = False, source_uuid: str | None = None, applicable_actions: list[str] = <factory>, children: list[TreeNode] = <factory>)[source]

Bases: BaseModel

Recursive tree representation of workspace contents.

applicable_actions: list[str]
children: list[TreeNode]
file_format: str
file_type: str
is_dir: bool
is_generated: bool
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str
path: str
registered: bool
source_uuid: str | None
uuid: str | None
class dartfx.workspace.Visibility(*values)[source]

Bases: StrEnum

Visibility scope for spaces and workspaces.

PRIVATE = 'private'
PUBLIC = 'public'
TEAM = 'team'
class dartfx.workspace.Workspace(path: Path | str | None = None)[source]

Bases: object

Facade for managing workspace initialization and orchestrating scans, programmatic file/resource operations, queries, and Knowledge Base interactions.

copy_path(src_rel: str, dst_rel: str, quota_bytes: int | None = None, *, allow_policy_override: bool = False) → Path[source]

Copy a file or directory inside the workspace with optional quota and policy enforcement.

create_archive(rel_path: str = '.', *, output_zip_path: Path | None = None, include_kb: bool = False) → Path[source]

Package a workspace file, directory, or full workspace as a ZIP archive.

export_rdf(uuid_val: UUID | str | None = None, rdf_format: str = 'turtle') → str[source]

Serialize RDF metadata for a single resource or the full workspace graph.

classmethod find_nearest_initialized_path(path: Path) → Path | None[source]

Returns the closest initialized workspace at or above path.

classmethod find_parent_initialized_path(path: Path) → Path | None[source]

Returns the nearest initialized parent workspace above path (excluding path).

get_resource_detail(identifier: str) → ResourceDetail[source]

Lookup detailed Knowledge Base metadata by resource UUID or relative path.

get_settings() → WorkspaceSettings[source]

Load workspace settings from .dartfx/settings.json, or return defaults.

get_tree(target_path: str = '.', *, max_level: int | None = None, type_filter: str | None = None, format_filter: str | None = None, mime_filter: str | None = None) → TreeNode[source]

Build a recursive directory tree representation of the workspace.

ingest_file(content: bytes | BinaryIO, dest_rel_path: str, *, overwrite: bool = False, auto_scan: bool = True, quota_bytes: int | None = None, allow_policy_override: bool = False) → FileEntry[source]

Safely write uploaded bytes/stream into the workspace with quota, policy, and KB indexing.

classmethod init(path: Path | None = None, create_dirs: bool = False) → Workspace[source]
is_initialized() → bool[source]
property kb: KnowledgeBase
list_files(target_path: str = '.', *, recursive: bool = False, show_all: bool = False, glob_pattern: str | None = None, type_filter: str | None = None, format_filter: str | None = None, mime_filter: str | None = None, registered_only: bool | None = None) → list[FileEntry][source]

List files and directories in the workspace with optional filtering.

mkdir(rel_path: str) → Path[source]

Create a directory inside the workspace.

move_path(src_rel: str, dst_rel: str, *, cascade_artifacts: bool = True, allow_policy_override: bool = False) → Path[source]

Move or rename a file or directory while updating the Knowledge Base.

If cascade_artifacts is True and the source is a user dataset (not system-generated), any existing related system-generated artifacts (FAIRify / ReadStat metadata) are also renamed and moved to match the new dataset name/location, preserving their persistent UUIDs.

preview_file(rel_path: str, mode: str = 'head', num_lines: int = 10) → FilePreview[source]

Return head or tail text lines from a workspace file.

query_sparql(query_str: str) → SparqlResult[source]

Execute a read-only SPARQL query against the workspace Knowledge Base.

query_tabular(sql: str, max_rows: int = 500) → TabularQueryResult[source]

Execute a read-only SQL query against CSV/TSV/Parquet files in the workspace.

remove_path(rel_path: str, *, delete_artifacts: bool = True) → list[str][source]

Remove a file or directory inside the workspace and prune the Knowledge Base.

If delete_artifacts is True and the target is a user-provided file (not system-generated), any existing related FAIRification / system-generated artifacts (such as .stats.csv, .schema.json, .freqs.csv, .idx, .description.md, .readstat.json) will also be deleted.

Returns:

The relative paths of all deleted files/directories.

Return type:

list[str]

resolve_download_path(path_or_uuid: str) → tuple[Path, str][source]

Resolve a workspace file by relative path or KB UUID and return (abs_path, mime_type).

resolve_safe_path(rel_path: str | Path, allow_dartfx: bool = False) → Path[source]

Resolve a workspace-relative path safely without escaping the workspace root.

run_fairify(source_rel_path: str, describe: bool = False) → TaskEvent[source]

Programmatically execute the qsv fairify workflow on a workspace data file.

run_readstat(source_rel_path: str, output_rel_path: str | None = None, *, extract_metadata: bool = False, force: bool = False) → TaskEvent[source]

Programmatically execute readstat conversion or metadata extraction.

run_tocsv(source_rel_path: str, *, force: bool = False) → TaskEvent[source]

Programmatically convert a readstat-supported statistical file to CSV.

save_settings(settings: WorkspaceSettings) → WorkspaceSettings[source]

Persist workspace settings to .dartfx/settings.json.

scan()[source]

Triggers a filesystem scan and KB synchronization.

property scanner: Scanner
property settings_path: Path

Path to the workspace settings JSON file inside .dartfx.

stats() → WorkspaceStats[source]

Computes stats based on the latest knowledge base data and filesystem probe.

total_usage_bytes() → int[source]

Compute total non-internal user storage used in bytes.

update_resource_metadata(uuid_val: UUID | str, *, file_type: str | None = None, file_format: str | None = None, attributes: dict[str, str] | None = None) → ResourceDetail[source]

Update classification or custom attributes for a registered KB resource.

update_settings(patch: dict[str, Any]) → WorkspaceSettings[source]

Deep-merge a partial settings dictionary into the workspace settings and save.

exception dartfx.workspace.WorkspaceAccessDeniedError[source]

Bases: PermissionError

Raised when a principal lacks permission for an action on a workspace or space.

class dartfx.workspace.WorkspaceConfig(*, id: str, slug: str, name: str, path: Path, space_id: str | None = None, visibility: Visibility = Visibility.PUBLIC, is_ephemeral: bool = False, storage_quota_bytes: int | None = None, owner_id: str | None = None, team_id: str | None = None)[source]

Bases: BaseModel

Configuration metadata and ownership settings for a managed Workspace.

id: str
is_ephemeral: bool
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str
owner_id: str | None
path: Path
slug: str
space_id: str | None
storage_quota_bytes: int | None
team_id: str | None
visibility: Visibility
exception dartfx.workspace.WorkspacePathTraversalError[source]

Bases: ValueError

Raised when a requested path attempts to escape the workspace root or access restricted internals.

class dartfx.workspace.WorkspaceSettings(*, version: int = 1, rename: RenamePolicy = <factory>, ingestion: IngestionPolicy = <factory>)[source]

Bases: BaseModel

Extensible workspace-level configuration and governance policies.

ingestion: IngestionPolicy
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

rename: RenamePolicy
version: int
class dartfx.workspace.WorkspaceStats(*, total_files: int, total_size_bytes: int, registered_count: int, registered_size_bytes: int, unregistered_count: int, unregistered_size_bytes: int, types_info: dict[FileType, FileTypeStats])[source]

Bases: BaseModel

Aggregation statistics for a workspace.

model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

registered_count: int
registered_size_bytes: int
total_files: int
total_size_bytes: int
types_info: dict[FileType, FileTypeStats]
unregistered_count: int
unregistered_size_bytes: int
class dartfx.workspace.ZoneRule(*, pattern: str, allowed_types: list[str] = <factory>, disallowed_types: list[str] = <factory>, allowed_formats: list[str] = <factory>, disallowed_formats: list[str] = <factory>, allowed_extensions: list[str] = <factory>, disallowed_extensions: list[str] = <factory>, max_size_bytes: int | None = None, allow_unrecognized: bool = True, allow_system_generated: bool = True)[source]

Bases: BaseModel

Content governance rule for a workspace path pattern (e.g. ‘data/’, ‘docs/’).

allow_system_generated: bool
allow_unrecognized: bool
allowed_extensions: list[str]
allowed_formats: list[str]
allowed_types: list[str]
disallowed_extensions: list[str]
disallowed_formats: list[str]
disallowed_types: list[str]
max_size_bytes: int | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

pattern: str
dartfx.workspace.detect_installed_tools() → dict[str, dict[str, str | bool | None]][source]

Inspect external CLI tools and optional analytical libraries in the runtime environment.

dartfx.workspace.hello(name: str = 'World') → str[source]

Return a greeting.

dartfx.workspace.run_fairify_task(ws: Workspace, task_id: str, workspace_id: str, *, source_rel_path: str, describe: bool = False, force: bool = False, on_event: Callable[[TaskEvent], None] | None = None, cancel_check: Callable[[], bool] | None = None) → TaskEvent[source]

Execute the qsv fairify workflow on a workspace tabular file emitting TaskEvents.

dartfx.workspace.run_readstat_task(ws: Workspace, task_id: str, workspace_id: str, *, source_rel_path: str, output_rel_path: str | None = None, extract_metadata: bool = False, force: bool = False, on_event: Callable[[TaskEvent], None] | None = None, cancel_check: Callable[[], bool] | None = None) → TaskEvent[source]

Execute readstat conversion or extract_metadata emitting structured TaskEvents.

dartfx.workspace.run_scan_task(ws: Workspace, task_id: str, workspace_id: str, *, target_path: str = '.', clean: bool = False, on_event: Callable[[TaskEvent], None] | None = None, cancel_check: Callable[[], bool] | None = None) → TaskEvent[source]

Execute a workspace scan and KB synchronization emitting structured TaskEvents.

dartfx.workspace.run_tocsv_task(ws: Workspace, task_id: str, workspace_id: str, *, source_rel_path: str, force: bool = False, on_event: Callable[[TaskEvent], None] | None = None, cancel_check: Callable[[], bool] | None = None) → TaskEvent[source]

Convert a supported statistical file to CSV via readstat emitting TaskEvents.

async dartfx.workspace.stream_task(fn: Callable[[...], TaskEvent], *args: Any, **kwargs: Any) → AsyncIterator[TaskEvent][source]

Run any synchronous task runner in a worker thread and asynchronously stream its TaskEvents.