Metadata-Version: 2.1
Name: clickzetta-studio-utils
Version: 0.1.5
Summary: clickzetta-studio-utils
Requires-Python: >=3.10
Requires-Dist: clickzetta-connector>=1.0.28
Description-Content-Type: text/markdown

# clickzetta-studio-utils

`clickzetta-studio-utils` is a Python utility package built on top of `clickzetta-connector`. It currently provides a lightweight wrapper around ClickZetta's `FsUtil`, making it convenient to work with Volume files from Studio or scripts.

## Installation

This project requires Python `>=3.10`.

```bash
pip install clickzetta-studio-utils
```

For local development, use `uv` to install dependencies:

```bash
uv sync --dev
```

## Basic Usage

```python
from clickzetta.connector.v0.connection import connect
from clickzetta_studio_utils._utils import _Utils

conn = connect(
    username="<USERNAME>",
    password="<PASSWORD>",
    service="<SERVICE>",
    instance="<INSTANCE>",
    workspace="<WORKSPACE>",
    schema="<SCHEMA>",
    vcluster="<VCLUSTER>",
)

try:
    dbutils = _Utils(conn)

    dbutils.fs.put("volume://<VOLUME>/data/1.txt", "hello clickzetta")
    print(dbutils.fs.ls("volume://<VOLUME>/data/"))
    print(dbutils.fs.head("volume://<VOLUME>/data/1.txt"))
    dbutils.fs.rm("volume://<VOLUME>/data/1.txt")
finally:
    conn.close()
```

`dbutils.fs` delegates filesystem operations to `clickzetta-connector`. `dbutils.fs.mounts()` is currently a compatibility stub and returns an empty list because Studio does not have a mount registry yet.

Studio can refresh a reused session's filesystem with `dbutils.fs = refreshed.fs`. This preserves the existing `widgets`, `jobs.taskValues`, and `notebook` objects. A temporary replacement runtime must use `init_dbutils(config, bind_builtins=False)` so it does not overwrite the session's built-in `dbutils`/`czutils` aliases.

Before each cell, Studio calls `dbutils.set_runtime_config(...)` with the current run's `runtime`, `taskValues` producer mappings, and `dbutilsApi` endpoint. A new instance or execution attempt clears the local task-value cache and old producer bindings; cells in the same attempt keep sharing values. Within the same attempt, omitted `taskValues.currentProducer` or `taskValues.producers` fields keep their existing values; an explicit empty mapping clears that field. Producer mappings come from the scheduler's existing instance bindings, not from a search for the latest successful run. Changing `vcluster` invalidates the cached filesystem connection, so the next filesystem operation uses the new cluster. Credential replacement through `fs` assignment also keeps the replacement connection configuration for later cluster changes.

The package remains compatible with the older Studio calls/configuration used with commit `9a95df9f`: no new initialization argument is required, and older `set_runtime_context(...)` calls still work without `set_runtime_config(...)`. Missing `runtime`, `taskValues`, `dbutilsApi`, or `lakehouseConnection` sections do not prevent initialization or local widget/task-value use. A filesystem operation still needs the same Lakehouse connection fields as before; no credentials or instance bindings are inferred.

Per-cell producer-map and filesystem VC synchronization need the matching Worker/NB Server changes, but upgrading this package does not require upgrading Studio at the same time. Install the updated package before enabling the new Cell bootstrap, and restart existing kernels so they do not retain the old imported class. This change does not require a `clickzetta-connector` code change.

## Notebook `dbutils.widgets`

Notebook runtimes can initialize a Databricks-like `dbutils.widgets` object from scheduler-provided runtime config.

```python
from clickzetta_studio_utils import init_dbutils

dbutils = init_dbutils(
    {
        "runtime": {
            "tenantId": 1,
            "projectId": 2,
            "scheduleTaskId": 3,
            "scheduleInstanceId": 4,
            "executeLogId": 5,
        },
        "dbutilsApi": {
            "baseUrl": "http://scheduler-worker:8080",
        },
        "widgetValues": {
            "biz_date": "2026-07-27",
        },
    }
)

dbutils.widgets.text("biz_date", "2026-07-20", "Business Date")
print(dbutils.widgets.get("biz_date"))  # keeps the runtime value: 2026-07-27
```

Supported APIs:

```python
dbutils.widgets.text(name, defaultValue="", label=None)
dbutils.widgets.dropdown(name, defaultValue, choices, label=None)
dbutils.widgets.combobox(name, defaultValue, choices, label=None)
dbutils.widgets.multiselect(name, defaultValue, choices, label=None)
dbutils.widgets.get(name)
dbutils.widgets.getAll()
dbutils.widgets.remove(name)
dbutils.widgets.removeAll()
```

Widget declaration and removal events are posted to `POST /v1/dbutils/widgets/events` when `dbutilsApi.baseUrl` is configured. Event write failures are logged as warnings and do not change local widget behavior.

## Notebook `dbutils.jobs.taskValues`

Notebook runtimes can use `dbutils.jobs.taskValues` to persist values for downstream task instances and to share values across cells in the current Python kernel.

```python
dbutils.jobs.taskValues.set("row_count", 100)

print(dbutils.jobs.taskValues.get("row_count"))
print(dbutils.jobs.taskValues.get(taskKey="extract_orders", key="row_count", default=0))
```

With a configured `dbutilsApi.baseUrl`, tenant ID, execution-log ID, and complete current-producer identity, `set()` first persists serialized JSON through `POST /v1/dbutils/task-values/set`, checks for the supported acknowledgement (`true` or `"success"`), and then updates local state. Network or business failures raise an error and leave the previous local value unchanged. Without an endpoint or complete producer context, task values remain local-only, including on older Studio versions. `get(taskKey=...)` reads upstream values through `POST /v1/dbutils/task-values/get` only when the scheduler supplies a complete producer mapping. A missing value or mapping uses the supplied default; a failed server request raises an error instead of silently returning that default. Both legacy unwrapped response payloads and `CommonResult.data` payloads are accepted.

With a configured callback endpoint, tenant ID, and execution-log ID, `dbutils.notebook.exit(value)` sends the exit value to the worker and raises the normal Notebook exit signal only after a successful acknowledgement. A failed or missing acknowledgement is an error, not a successful exit. If older Studio did not supply that callback context, `exit()` retains its local exit signal without making an invalid request; no remote exit value is persisted. Widget UI event writes remain best-effort: failures are logged without failing the cell.

`dbutils.notebook.run(path, timeout_seconds=0, arguments=None)` validates its timeout before submission and requires an execution-log ID before polling. An older worker may omit `instanceId`; it resolves the instance from `executeLogId` instead. Status responses must contain a boolean `terminal` field; a malformed response fails instead of polling indefinitely. Zero means no client-side timeout; a positive timeout uses a monotonic clock. Timeout or cancellation sends a single best-effort kill request. Its response is not validated, and request exceptions are only logged; cleanup never replaces the original run error or cancellation.

## Development

Common commands:

```bash
# Check code style and lint issues
uv run ruff check .

# Format Python files
uv run ruff format .

# Run the full test suite
make test

# Clean dist/ and build source and wheel distributions
make build

# Build, validate, and upload to PyPI with a project-scoped API token
export TWINE_USERNAME="__token__"
export TWINE_PASSWORD="pypi-..."
make publish
```

## Testing Notes

The test suite includes integration tests that connect to a real ClickZetta service and operate on temporary Volumes. Before running them, make sure that:

- Connection parameters are valid, and the account has permission to create and delete Volumes and read/write files.
- Personal, production, or long-lived credentials are not committed. Prefer environment variables or local untracked configuration when credentials are needed.
- You run targeted tests for the code you changed first, then run the full test suite when appropriate.

## Project Information

- Package name: `clickzetta-studio-utils`
- Import module: `clickzetta_studio_utils`
- Runtime dependency: `clickzetta-connector>=1.0.28`
- Build backend: `pdm-backend`
