Metadata-Version: 2.5
Name: h2o-connector-service
Version: 0.5.0a1
Summary: Python client SDK for the H2O Connector Service — create connectors, open connections, and stream extracted data
Project-URL: Source, https://github.com/h2oai/connector-service
Project-URL: Issues, https://github.com/h2oai/connector-service/issues
Author-email: "H2O.ai, Inc." <support@h2o.ai>
Keywords: blob-storage,connector,data-extraction,data-ingestion,delta-lake,gRPC,h2o,hive,postgresql,snowflake
Classifier: Development Status :: 4 - Beta
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: googleapis-common-protos>=1.72
Requires-Dist: grpcio>=1.64
Requires-Dist: h2o-authn>=3.1.0
Requires-Dist: h2o-cloud-discovery>=3.3.0
Requires-Dist: httpx>=0.27
Requires-Dist: protobuf<8,>=6.33.5
Requires-Dist: pydantic>=2
Provides-Extra: datatable
Requires-Dist: datatable>=1.0; extra == 'datatable'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=9.0.3; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff==0.15.22; extra == 'dev'
Requires-Dist: types-grpcio>=1.0; extra == 'dev'
Requires-Dist: types-protobuf>=4.24; extra == 'dev'
Provides-Extra: h2o
Requires-Dist: h2o>=3.44; extra == 'h2o'
Requires-Dist: pandas>=1.5; extra == 'h2o'
Requires-Dist: pyarrow>=14; extra == 'h2o'
Provides-Extra: pandas
Requires-Dist: pandas>=1.5; extra == 'pandas'
Provides-Extra: parquet
Requires-Dist: pyarrow>=14; extra == 'parquet'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=1.0; extra == 'test'
Requires-Dist: pytest-cov>=5.0; extra == 'test'
Requires-Dist: pytest>=9.0.3; extra == 'test'
Requires-Dist: respx>=0.21; extra == 'test'
Description-Content-Type: text/markdown

# h2o-connector-service

Python client for the H2O Connector Service. Use it to create connectors, open connections, and stream data to and from
a data source.

```bash
pip install h2o-connector-service
```

## Connect

### H2O AI Cloud

Pass your environment URL and platform token. The client finds the connector service URL through discovery, on any
domain, and refreshes the access token for you.

```py
from h2o_connector_service import Client

client = Client(
    environment="https://cloud.h2o.ai",
    platform_token="<your platform token>",
    ssl_ca_cert="/path/to/ca.pem",  # optional, for a private CA
)
```

With no arguments the client finds the environment by itself: inside an H2O notebook from the env vars
`H2O_CLOUD_ENVIRONMENT` and `H2O_CLOUD_CLIENT_PLATFORM_TOKEN`, and elsewhere from the H2O CLI config
(`~/.h2oai/h2o-cli-config.toml`, or the file named by `H2OCONFIG` or `config_path=`). If none of these is set,
`Client()` raises `ValidationError` listing the options.

```py
client = Client()
client = Client(config_path="~/work/h2o-cli-config.toml")
```

`h2o_cloud_url=`, `refresh_token=` and `ssl_cacert=` still work for now, with a `DeprecationWarning`. They are the old
names of `environment=`, `platform_token=` and `ssl_ca_cert=`, the names `h2o_engine_manager.login()` and
`h2o_secure_store.login()` use (`h2o_mlops.Client` still takes the old ones).

### A known service URL

Pass `connector_service_url=` when you already know the address of the connector service itself. The client uses the
URL as given, never runs discovery, and sends the token as a static bearer token.

```py
client = Client(
    connector_service_url="https://connector-service.cloud.h2o.ai",
    platform_token="<a valid access token>",
)
```

Add `verify_ssl=False` for a local or test deployment that uses a self-signed certificate.

### Your own token provider

If your service already manages OIDC tokens, pass a callable that takes no arguments. The client calls it on every
request, so returning a fresh access token keeps token expiry invisible to the SDK. You cannot use `platform_token=` and
`token_provider=` together.

```py
client = Client(
    connector_service_url="https://connector-service.cloud.h2o.ai",
    token_provider=lambda: my_auth_layer.current_access_token(),
)
```

An `h2o_authn.TokenProvider` is such a callable, so one provider can serve this client and `h2o_mlops`, `h2o_drive` or
`h2o_engine_manager` at the same time. With `environment=` instead of `connector_service_url=`, the client still finds
the service URL through discovery and takes the token from your provider.

```py
import h2o_authn
import h2o_discovery

discovery = h2o_discovery.discover(environment="https://cloud.h2o.ai")
provider = h2o_authn.TokenProvider(
    refresh_token="<your platform token>",
    issuer_url=discovery.environment.issuer_url,
    client_id=discovery.clients["platform"].oauth2_client_id,
)
client = Client(environment="https://cloud.h2o.ai", token_provider=provider)
```

### Service identity

A platform service that runs in the same Kubernetes cluster can authenticate with its ServiceAccount token. The client
sends the token in the `x-h2o-service-authorization` header, and the server checks it against its allowlist. This path
needs `connector_service_url=`.

```py
def read_projected_sa_token() -> str:
    with open("/var/run/secrets/kubernetes.io/serviceaccount/token") as f:
        return f.read().strip()

# Service only. Every operation belongs to the service identity.
client = Client(
    connector_service_url="https://connector-service.cloud.h2o.ai",
    service_token_provider=read_projected_sa_token,
)

# On behalf of a user. The service vouches for the call and the user token
# gives the identity. If the user token is invalid the server rejects the
# request. It never falls back to the service identity.
client = Client(
    connector_service_url="https://connector-service.cloud.h2o.ai",
    service_token_provider=read_projected_sa_token,
    token_provider=lambda: current_user_access_token(),
)
```

`whoami()` needs a user credential. It raises `ValidationError` on a service-only client.

### Workspace id

Workspace id is not a constructor argument. Pass it on every workspace-scoped call, for example
`client.connectors.list(workspace_id)` and `client.open_session(workspace_id=..., ...)`. An empty
workspace id raises `ValidationError` locally, before any request is sent.

If your code works in one workspace, bind it once. `client.workspace(workspace_id)` returns a `WorkspaceClient` whose
`connectors`, `connections`, `workers` and `pipelines` have the same methods without the workspace argument, and whose
`open_session` and `provision_session` take no `workspace_id`:

```py
ws = client.workspace("my-workspace")
for connector in ws.connectors.all():
    print(connector.id)
with ws.open_session(connector="pg-prod", worker="w-pg", extraction={"query": "SELECT 1"}) as session:
    rows = list(session.stream_records())
```

### Timeouts and deadlines

Two constructor arguments bound HTTP requests, and they answer different questions:

- `timeout=` is the per-operation httpx timeout (default 60 s read / 10 s connect). The read
  component is measured **per received chunk**, so it is an idle timeout, not a total one.
- `request_deadline=` is an end-to-end wall-clock bound per request. When set, every timeout
  component is clamped to it and the response body is read under it, so a server that trickles
  the body can no longer keep a request alive indefinitely. Exceeding it raises
  `RequestDeadlineExceeded`, a `DeadlineExceeded` that is also an `httpx.TimeoutException`,
  so existing `except httpx.TransportError` handling keeps working.

```py
client = Client(
    connector_service_url="https://connector-service.cloud.h2o.ai",
    platform_token="<a valid access token>",
    request_deadline=30.0,
)
```

Boundaries to know: `watch()` streams are exempt (a healthy watch can be silent for hours, and any
finite end-to-end bound would kill it). Two residuals can extend how long a call *blocks*, though a
late response still raises rather than returning success: a hung token refresh inside your
`token_provider` (bounded only by that provider's own HTTP timeouts), and a server that trickles
response *header* bytes (each byte resets the per-read timeout, and no deadline check can run while
headers are being read).

## Resources

Every model has `.id`, its own id, and `.name`, its full resource path (`workspaces/<ws>/connectors/<id>`). Wherever a
method takes a resource (`get`, `update`, `delete`, `preview`, and the `connector=` / `worker=` of a connection or a
pipeline stage) it accepts the id, `"<plural>/<id>"`, the full path, or the model. `get`, `update` and `delete` refuse a
path that names another workspace: pass that workspace instead.

The `connector=` and `worker=` of a connection or a pipeline stage may name one in another workspace, by its full path or
its model, when you hold `connectors/USE` or `workers/USE` there (the Owner and Writer roles do) and its
`workspace_access_control` allows your workspace. The connection still lives in your workspace. Set
`workspace_access_control={"allowed_workspace_ids": [<own workspace>]}` on a connector or worker to keep it in its own
workspace. Incremental sync is the exception: a sync run needs a connector in its own workspace. To see what your
workspace may use in another one, list there with `usable_from_workspace_id`:
`client.connectors.all("analytics-ws", usable_from_workspace_id="my-ws")` (also on `workers`).

```py
shared = client.connectors.get("analytics-ws", "pg-warehouse")
with client.open_session(
    workspace_id="my-ws",
    connector=shared,
    worker="workspaces/analytics-ws/workers/pg",
    extraction={"query": "SELECT * FROM trips"},
) as session:
    df = session.stream_to_pandas()

connection = client.connections.get(workspace, "conn-1")
connector = client.connectors.get(workspace, connection.connector)  # the full path works in its own workspace
```

`create()` and `update()` take typed keyword arguments. Metadata is flat: `name=`, `display_name=`, `description=`,
`labels=` and `annotations=`. `update()` sends only the fields you pass, and derives the update mask from them. An
unknown keyword raises `ValidationError`; `extra={...}` sends fields this SDK version does not know yet.

```py
client.connectors.update(workspace, "pg", display_name="Postgres (prod)", labels={"team": "data"})
```

Connections and pipelines have no `update`, and data source profiles are read only. Durations (`default_max_run_duration`,
`timeout=` and the like) take seconds, a `timedelta` or a string such as `"30s"`, and read back as `timedelta`.

`connection.watch()` streams a connection's status changes, as `pipeline.watch()` does for a pipeline. It ends after the
first event in which the connection is COMPLETED, FAILED, CANCELLED or PRECONDITION_FAILURE, including the first event, so
a connection that has already finished yields one event (none with `include_initial=False`); a pause does not end it. Each event carries the connection at that moment, ready for
`.cancel()` and the other methods.

```py
for event in connection.watch():
    print(event.event_type, event.connection.status, event.message)
```

`client.service_settings()` says whether templates are in use (`templates_enabled`) and whether a connector may hold a
credential in plain text (`plaintext_credentials_allowed`), so a tool can skip a request the server would refuse.

### Sign in as the user

A connector whose credentials name a Secure Store OAuth client reads the source as the calling user.
`client.oauth_clients.all()` lists the OAuth clients you can see, to pick one for such a connector. Before a connection,
check whether you are signed in, and open `sign_in_uri` in a browser when you are not; the address signs in whoever
opens it, so do not share, print or log it. `sign_out()` makes your next connection on that OAuth client ask again, for example to change account.

```py
import webbrowser

status = client.connectors.user_sign_in(workspace, "sharepoint-docs")
if not status.signed_in:
    # The address signs in whoever opens it: open it, never print or log it.
    webbrowser.open(status.sign_in_uri)
client.connectors.sign_out(workspace, "sharepoint-docs")
```

## Errors

Every error the SDK raises is a `ConnectorServiceError`. Server errors arrive as the subclass that matches their gRPC
status, over REST and gRPC alike, so you catch by meaning:

| Class | Raised when |
|---|---|
| `ValidationError` | an argument is rejected before any request is sent (also a `ValueError`) |
| `SessionError` | a session method is called on a closed session, or a second read is started |
| `Unauthenticated` | the token is missing or invalid; `OAuthLoginRequired` is the subclass for a connection that needs a user sign-in |
| `PermissionDenied` | the caller may not do this |
| `NotFound` / `AlreadyExists` | the resource does not exist / already exists |
| `InvalidArgument` | the server rejected an argument |
| `FailedPrecondition` | the resource is in the wrong state, for example a worker that failed before it was ready |
| `ResourceExhausted` | a quota or capacity limit was reached |
| `Unavailable` | the service or worker could not be reached; retrying may succeed |
| `DeadlineExceeded` | the operation did not finish in time; `RequestDeadlineExceeded` is the client-side `request_deadline` |
| `Internal` | the server failed while handling the request |
| `StreamTruncated` | a read stream closed without its end-of-stream message |

A status with no class of its own raises `ConnectorServiceError`. `grpc_code` and `status_code` say which status it
was, and `request_id` carries the server's request id for a support request.

```py
from h2o_connector_service import AlreadyExists, NotFound

try:
    connector = client.connectors.get(workspace, "pg")
except NotFound:
    connector = client.connectors.create(workspace, name="pg", data_source_type="postgresql", data_source_config=cfg)
```

## Read data

A connection needs three parts:

- a **Connector**: the data source config
- a **Worker**, created from a **WorkerTemplate**. A dynamic Worker starts one pod per connection.
- an **ExtractionConfig**: what to read

Connectors and Workers are long-lived. A platform admin creates them once. End users only call `open_session(...)`,
which creates one connection per stream. See `examples/quickstart.py` for a runnable version.

```py
from h2o_connector_service import Client

client = Client(environment="https://cloud.h2o.ai", platform_token="...")
workspace = "my-workspace"

# ── ADMIN: create the long-lived resources ───────────────────────────────

# 1. WorkerTemplate (global): image and pod defaults
wt = client.worker_templates.create(
    name="wt-pg",
    image="353750902984.dkr.ecr.us-east-1.amazonaws.com/h2oai-connectorservice-workerpostgresql:latest",
    pull_policy="IfNotPresent",  # K8s short form or the full IMAGE_PULL_POLICY_* enum
    supported_data_source_types=["postgresql"],
    default_resources={"cpu": "250m", "memory": "512Mi"},
    enabled=True,
)

# 2. Connector (workspace): data source type and driver-native config
connector = client.connectors.create(
    workspace,
    name="pg",
    data_source_type="postgresql",
    data_source_config={
        "PGHOST": "db.example.com",
        "PGPORT": 5432,  # numbers and booleans are sent as text
        "PGDATABASE": "mydb",
        "PGUSER": "postgres",
        "PGPASSWORD": "secret",  # read this from env or SecureStore in real code
    },
)

# 3. Worker (workspace): built from the WorkerTemplate above
worker = client.workers.create(
    workspace,
    name="w-pg",
    worker_template=wt,  # a model, an id, or "workerTemplates/<id>"
)

# ── END USER: open one session, then stream ──────────────────────────────

# 4. open_session creates the Connection, waits for WORKER_READY, and on exit
#    deletes only the Connection. The other resources stay.
with client.open_session(
    workspace_id=workspace,
    connector=connector,
    worker=worker,
    extraction={"query": "SELECT * FROM my_table", "batch_size": 100},
) as session:
    for row in session.stream_records():
        print(row)  # {"id": 1, "created": datetime(..., tzinfo=UTC), "amount": Decimal("9.50"), ...}

# 5. Delete the long-lived resources when you no longer need them.
worker.delete()
connector.delete()
wt.delete()
```

To read from blob storage, pass paths instead of a query:

```py
extraction = {"paths": {"paths": [{"pattern": "data/"}]}}
```

A pattern ending in `/` or `*` is a prefix. Only a trailing `*` works. There are no globs: a `*` anywhere else is a
literal character. Any other pattern is one exact object key.

### Let the server pick the worker

`worker` is optional in `open_session`, `connections.create` and `preview`. Left out, the server picks a worker of the
workspace that you may use, that is not draining or suspended, and whose worker template lists the connector's data
source type: a STATIC worker first, then the one created first. The connection names the worker it got. When no worker
qualifies, the call fails with `FailedPrecondition` naming the data source type.

To offer only the connectors you can read from now, list them with `servable=true`. The server runs the checks of a
connection without a worker for each one, including your identity: a service caller does not see a connector that
signs in as the user. `resolved_data_source_type` is the connector's type, or its template's, with aliases normalised;
look its data source profile up by it.

```py
page = client.connectors.list(workspace, filter="enabled=true AND servable=true")
for connector in page.items:
    with client.open_session(workspace_id=workspace, connector=connector, extraction=...) as session:
        ...
```

## Preview before you connect

`preview` answers "will this extraction give me what I think it will?" without
creating anything. The server builds a short-lived connection of its own, reads
a bounded sample, and deletes it. Nothing is persisted and no existing
connection is touched.

```py
preview = client.connectors.preview(
    "my-workspace",
    "my-connector",
    worker="my-worker",
    extraction={"query": "SELECT * FROM trips"},
    max_rows=20,                 # default 100, server maximum 1000
)

for column in preview.columns():
    print(column, end="\t")
for row in preview.rows:
    print([row.get(c) for c in preview.columns()])

if preview.truncated:
    print("there is more data than this")
```

Or from a connector you already hold: `connector.preview(worker=..., extraction=...)`. Leave `worker` out and the
server picks one, as for a connection (see [Let the server pick the worker](#let-the-server-pick-the-worker)).

`preview.rows` hold the same Python values a stream of the same extraction yields; see [Values](#values).

Use `preview.columns()` rather than reading the schema's field names directly.
A row is a JSON object and cannot hold the same key twice, so the server renames
duplicate columns by position: a schema naming two columns `id` produces the
row keys `id` and `id_2`. `columns()` mirrors that, so every name it returns
indexes into the rows.

For a blob source the sample comes back as `preview.raw` instead: the object's
identity (`file_name`, `content_type`, `file_size`, and `document` for sources
that report per-item metadata) plus `head`, the leading bytes, already
base64-decoded.

Two things to expect:

- **It is slow.** Preview waits for a worker and then for a real read. A
  STATIC-mode worker answers in seconds from its running pool pod; a DYNAMIC
  worker has to start one first. The call carries its own 300s timeout for that
  reason. A client-level `request_deadline` would not have covered it, since
  the SDK only ever clamps timeout components downwards, never raises them.
  Pass `timeout=` to override.
- **There is no `connection.preview()`.** A read that drains its
  source reports a connection-terminal `COMPLETED`, so previewing over a
  connection you depend on would invalidate its tokens and tear down its
  worker. Preview is anchored on the connector for exactly that reason.

Runnable version: [examples/preview.py](examples/preview.py).

## Read a session

A session reads its connection once. The first `stream_*` call claims the read, and a second one raises
`SessionError`; open a new session to read again. `session.schema()` fetches the schema without reading and does not
count.

A session over a connection you created yourself, `ConnectorSession(client=client, connection=connection)`, deletes
that connection when it closes, as `open_session` does. Pass `owns_connection=False` to keep it: the session then
closes only its own transport, and the connection stays yours to inspect, pause, resume, read with another session, or
delete.

### Values

Every read returns the same Python types, whether it is a stream, a frame or a preview:

| Column type | Python value |
|---|---|
| integer | `int` |
| float | `float` |
| decimal | `decimal.Decimal` |
| text, UUID, interval | `str` |
| binary | `bytes` |
| boolean | `bool` |
| timestamp, timestamp with time zone | `datetime`, timezone-aware, in UTC |
| date | `datetime.date` |
| time | `datetime.time` |
| JSON | the parsed value (`dict`, `list`, ...) |
| array, map, struct | `list` or `dict`, decoded element by element |
| null | `None` |

Writes take the same types. `decode_value` and `encode_value` expose the table for a cell you hold yourself.

Keys are the schema's column names. A repeated name gets its position appended (`id`, `id_2`), as in a preview, and a
source with no schema names its columns `column_1`, `column_2`, and so on.

### Records

```py
for row in session.stream_records(limit=1000):  # limit is optional
    ...
```

`stream_batches()` yields the stream as the worker batched it. Each `RecordBatch` carries its `records`, the
stream's `schema`, and for SharePoint, Confluence and other document sources, the item's `document` metadata and ACLs.
The worker sends `document` once per item; every batch of that item carries it, so `batch.document.acl` is there on
whichever batch you look at, and a new item starts where `document.item_id` changes.

### Files and frames

Each call below is a complete read of the session. Pick one:

```py
# CSV file. Rows are written as they arrive, so memory stays flat.
session.stream_to_csv("output.csv")

# pandas DataFrame. Integer and boolean columns use nullable dtypes; timestamps are datetime64[us, UTC].
# Needs: pip install h2o-connector-service[pandas]
df = session.stream_to_pandas()

# Parquet file. Column types come from the source schema.
# Needs: pip install h2o-connector-service[parquet]
session.stream_to_parquet("output.parquet")

# datatable Frame. Needs: pip install h2o-connector-service[datatable]
frame = session.stream_to_data_table()

# H2O Frame. Needs a running H2O cluster and h2o.init().
# Needs: pip install h2o-connector-service[h2o]
h2o_frame = session.stream_to_h2o_frame()
```

All of them take `limit=` to stop after that many rows.

### Objects

A blob or document source streams objects instead of records:

```py
# Each object written to a file under out_dir.
file_count, byte_count = session.stream_to_files("out_dir")

# Each object whole, with its metadata and ACLs when the source is a document source.
for obj in session.stream_objects():
    acl = obj.document.acl if obj.document else None
    index(obj.file_name, obj.data, obj.document, acl)

# Or the chunks themselves. An object arrives as one or more chunks with the same file_name.
for chunk in session.stream_chunks():
    ...
```

All three take `max_objects=` to stop after that many objects. `stream_objects` holds one object in memory at a time
and refuses one over `max_object_bytes=` (256 MiB by default); use `stream_to_files` or `stream_chunks` for large
objects. The `document` on a chunk is carried from the object's first chunk to its last.

### After the read

Once a read ends, `session.read_result` says what it delivered:

```py
rows = session.stream_to_csv("output.csv")
result = session.read_result
print(result.completed, result.records_received, result.total_records, result.records_per_second)
```

`records_received`, `bytes_received`, `objects_received` and `batches_received` are the client's own counts.
`total_records`, `total_bytes`, `total_files` and `reason` are what the worker reported when the stream ended, and are
`None` when it sent no end-of-stream frame, which is the case when the read stopped early. `completed` is `False` when
`limit=`, `max_objects=`, leaving the loop or an error ended the read before the stream did. `elapsed` runs from the
first request for data to the end of the read; the client pulls, so time spent on each batch counts.

For progress while a read is running, the worker reports counters to the connection every few seconds:

```py
stats = session.connection.refresh().stats
print(stats.units_processed, stats.units_per_second, stats.totals)
```

`refresh()` fetches the server's copy into the same object and returns it; it is on every model. `stats.totals` is
what the source announced it would send (`total_records`, `total_bytes` or `total_files`), or `None` when it could
not say.

### Incremental sync

A **sync state** remembers where the last read of a document source stopped, so the next read streams only what
changed. The server keeps the cursor; you keep nothing between runs. Sync is a worker capability: a source that does
not implement it refuses a connection that asks for it instead of running a full read.

Create one sync state per thing you keep in step (a search index, a collection), bound to the connector:

```py
state = client.sync_states.create("my-workspace", "eng-site-docs", connector="my-sharepoint")
```

Then open a session with `sync` in the extraction and read it with `stream_sync`. The first run is a full snapshot.
Every later run streams only what changed since the cursor the previous run left on the state:

```py
with client.open_session(
    workspace_id="my-workspace",
    connector="my-sharepoint",
    worker="my-sharepoint-worker",
    extraction={
        "generic": {
            "selector_kind": "sharepoint_drive",
            "selector": {"site_url": "https://contoso.sharepoint.com/sites/eng"},
        },
        "sync": {"sync_state": state, "include_unchanged": True},
    },
) as session:
    run = session.stream_sync("sync_out")

for synced in run.files:  # new or changed items, written under sync_out
    index(synced.path, synced.document)  # document: item_id, title, web_url, acl, ...
```

`sync_state` takes the state itself, its id or its full name. `run.result` says how to learn about deletions. Check
`full_resync` first, then `deletion_detection`:

| Field | What to do |
|---|---|
| `result.full_resync` is true | The run was a full snapshot: the first run, a reset state, an expired cursor, or the connector was edited since the last run. Treat it as a first run. Do not read it as a delta. |
| `DeletionDetection.NATIVE` | The source reported deletions itself. Apply the `ItemChangeKind.DELETE` entries in `run.changes`. |
| `DeletionDetection.BY_ABSENCE` | Every live item was listed, as content in `run.files` or as an `UNCHANGED` entry in `run.changes`. Delete every item you know that was not listed. |
| `DeletionDetection.NONE` | Nothing in this run says what was deleted. Delete nothing. |

```py
from h2o_connector_service import DeletionDetection, ItemChangeKind

result = run.result
if result is None:
    raise RuntimeError("the stream ended before its result, so the run was not committed")

listed = {f.document.item_id for f in run.files if f.document}
listed |= {c.document.item_id for c in run.changes if c.document}

if result.full_resync:
    replace_everything(run.files)
elif result.deletion_detection == DeletionDetection.NATIVE:
    for change in run.changes:
        if change.kind == ItemChangeKind.DELETE and change.document:
            remove(change.document.item_id)
elif result.deletion_detection == DeletionDetection.BY_ABSENCE:
    for item_id in known_item_ids() - listed:
        remove(item_id)
# DeletionDetection.NONE: delete nothing.
```

Two items can share one file name: an item deleted in this run and the item that replaced it arrive together, and
`stream_sync` has already written the replacement when the deletion is applied. Delete a file only when no item you
still hold maps to it; `LocalIndex` in the example does this.

The api-server commits the next cursor to the sync state when the connection completes. A run that fails or is
cancelled leaves the cursor where it was, and the next run covers the same window. One run at a time per state: a
second connection on the same state is refused while the first is active.

`state.reset()` clears the cursor so the next run is a full snapshot. Use it after you change the selector (a run
with a different selector than the first one is refused, because an old cursor over a new scope would hide
deletions outside it) or when the consumer lost its copy. `state.delete()` removes the record. There is no update:
every field a run changes is written by the server.

`"sync": {"metadata_only": True}` lists every item as an `UPSERT` entry with no content, for pickers and size
estimates, and needs no sync state. The other read methods refuse a sync connection and point at `stream_sync()`.
Whichever method read the connection, a sync result the worker sent is also on `session.read_result.sync`.

To fetch items the listing showed missing or stale without resetting the cursor, read them by id with the same
selector and no `sync`: `extraction={..., "item_ids": [...]}` (at most 1,000), then `stream_objects` (or
`stream_chunks` for large files). An id the selection no longer has is left out, and every object's `document` carries
the `version` the listing reported for it. A source
offers this when its profile sets `extraction.item_ids`; every source that syncs does.

Runnable version: [examples/quickstart_sync.py](examples/quickstart_sync.py).

## Write data

Open a session with `direction=Direction.WRITE` and a `write=` config. With an existing connector and worker, use
`open_session`:

```py
from h2o_connector_service import Direction, WriteMode

with client.open_session(
    workspace_id="my-workspace",
    connector="pg-prod",
    worker="w-pg",
    direction=Direction.WRITE,
    write={
        "tabular": {"target_table": "my_schema.my_table", "conflict_columns": ["id"]},
        "mode": WriteMode.UPSERT,
    },
) as session:
    result = session.write_records(records)
    print(result.rows_written, result.batches_acked)
```

`provision_session` creates every resource it needs (WorkerTemplate, Worker, Connector and Connection), waits for the
worker, and deletes them all in reverse order on exit. It works for reads too (`direction=Direction.READ` with
`extraction=`). It needs a worker image, either from `worker_image=` as below or from an env var. See
[Worker image](#worker-image).

```py
with client.provision_session(
    "postgresql",
    pg_cfg,
    workspace_id="my-workspace",
    direction=Direction.WRITE,
    write={"tabular": {"target_table": "my_schema.my_table"}, "mode": WriteMode.REPLACE},
    worker_image="353750902984.dkr.ecr.us-east-1.amazonaws.com/h2oai-connectorservice-workerpostgresql:latest",
) as session:
    session.write_records(records)
```

Write modes are `INSERT`, `UPSERT`, `APPEND`, and `REPLACE`. The default is `INSERT`, and `UPSERT` also needs
`conflict_columns`.

A cell can be `None`, `bool`, `int`, `float`, `str`, `bytes`, `datetime`, `date`, `time`, `Decimal`, `list`, `tuple` or
`dict`. A list or tuple goes on the wire as an array and a dict as a JSON document; worker-postgresql and
worker-snowflake store them as JSON text, so a JSONB or VARIANT column gets the document and a text column the
text. That needs worker-postgresql and worker-snowflake 0.4.0 or newer; an older sink stores NULL for them.

`write=` is a `WriteConfig`, the same one pipelines use: a `tabular` or `blob` target plus `mode`, `batch_size` and
`schema`. A schema is a column name to type name map such as `{"id": "int"}`, the `Schema` that a read session's
`session.schema()` returns, or the proto `Schema` JSON; a session folds it to the map and a pipeline sink sends the proto
form. Its values are the session's defaults.
`write_records` and `write_dataframe` use the tabular ones, and `write_bytes` and `write_file` the blob ones (`batch_size`
is then the chunk size), for any argument the call leaves out. A value passed to the call wins for that call, for
example `session.write_records(more, mode="APPEND")`. A blob write reports what it wrote in `result.bytes_written`
(`rows_written` is `None`); a record write reports `result.rows_written`.

```py
with client.provision_session(
    "s3",
    s3_cfg,
    workspace_id="my-workspace",
    direction=Direction.WRITE,
    write={"blob": {"target_url": "exports/report.csv", "content_type": "text/csv"}, "mode": WriteMode.REPLACE},
) as session:
    print(session.write_file("report.csv").bytes_written)
```

### Worker image

`provision_session` needs a container image to start the worker pod. The SDK has no
built-in default image, on purpose. An image name without a registry prefix makes kubelet pull from
`docker.io/library/<name>`, which fails on every managed cluster with `ErrImagePull` and no useful error message.

The client picks the image in this order:

1. The `worker_image=` argument, for a single call.
2. The `H2O_CONNECTOR_SERVICE_DEFAULT_WORKER_IMAGE_<TYPE>` env var, set once at deployment time. It must include the
   registry.

If neither is set, the call fails at once with a `ValidationError` that names the env var to set. The `<TYPE>`
suffix is the `connector_type` you passed, in upper case, with hyphens replaced by underscores. So `"postgresql"` reads
`..._POSTGRESQL` and `"delta-lake"` reads `..._DELTA_LAKE`.

Set the env var once per deployment, in the pod spec, in Helm values, or in the shell:

```bash
export H2O_CONNECTOR_SERVICE_DEFAULT_WORKER_IMAGE_POSTGRESQL=\
353750902984.dkr.ecr.us-east-1.amazonaws.com/h2oai-connectorservice-workerpostgresql:latest
```

The `:latest` tag is the latest released image. Pin a release tag if you need a fixed version.

Note the `353750902984.dkr.ecr.us-east-1.amazonaws.com/` prefix. Always write the registry and the organization in
full, even for a Docker Hub image (`docker.io/<org>/...`). A bare `h2oai-connectorservice-workerpostgresql:latest` is
what kubelet reads as `docker.io/library/...`, which is the failure this section warns about.

Use `worker_image=` when different call sites need different images, for example when you test a new worker build. It
overrides the env var.

## Move data server side

A **pipeline** moves data from a source to a sink inside the cluster. No bytes reach the client. Use it for exports
and loads where your process does not need to see the rows.

```py
pipeline = client.pipelines.create(
    "my-workspace",
    name="nightly-export",
    source={
        "connector": "connectors/my-pg",
        "worker": "workers/my-pg-worker",
        "extraction": {"query": "SELECT id, name FROM t ORDER BY id"},
    },
    steps=[
        {
            # A processor: a connector of type "csv" with no config, and a
            # worker running the processor-csv image.
            "connector": "connectors/my-csv",
            "worker": "workers/my-csv-processor",
            "process": {"process_kind": "serialize_csv"},
        }
    ],
    sink={
        "connector": "connectors/my-s3",
        "worker": "workers/my-blob-worker",
        "write": {"blob": {"target_url": "exports/out.csv"}, "mode": "WRITE_MODE_REPLACE"},
    },
)

# The pipeline exists from here on, so its cleanup belongs in a finally:
# watch() is a network call and can raise.
try:
    # Stream every status change, or poll with pipeline.wait_for_terminal().
    for event in pipeline.watch():
        # event.pipeline is None on a frame that carries no snapshot.
        if event.pipeline is not None:
            print(event.pipeline.status, event.message)
finally:
    # Try the delete first. It succeeds on a terminal pipeline, and it does
    # not depend on `pipeline.status`, which still holds the create-time value
    # unless something refreshed it. Only fall back to cancelling.
    # Deleting also deletes every stage of the pipeline.
    try:
        pipeline.delete()
    except Exception:                      # delete refuses a live pipeline
        # Do not stop on a cancel error: cancel() is a compare-and-swap and
        # fails whenever a concurrent transition wins the race, which is
        # normal, and the pipeline is heading for a terminal state anyway.
        with contextlib.suppress(Exception):
            pipeline.cancel()
        with contextlib.suppress(Exception):
            pipeline.wait_for_terminal(timeout=300.0)
        pipeline.delete()
```

(`import contextlib`, and see `examples/quickstart_pipeline.py` for the same
shape with logging instead of suppression.)

`delete()` needs a **terminal** pipeline, so a run that is still live has to be
cancelled first. `examples/quickstart_pipeline.py` shows the full shape: try
the delete, and only if it is refused, cancel, wait for terminal, and delete
again. Do not give up on the delete when the cancel raises: `cancel()` is a
compare-and-swap server-side and fails whenever a concurrent status transition
wins the race, which is normal.

Each step is a connector, a worker and a `process` (`process_kind` plus an optional `config` dict). The api-server
creates one stage for the source, one for each step and one for the sink, and the runner streams them in that order. The steps' process kinds and their config keys are listed in the data source profiles
(`process_kinds`). A tabular source writing to a blob sink needs a serializer step: `serialize_csv` (connector type
`csv`, worker image `processor-csv`) or `serialize_parquet` (connector type `parquet`, worker image
`processor-parquet`). A blob source writing to a tabular sink needs a reading step from the same two images: `parse_csv`
or `parse_parquet`. With no steps the source's output goes to the sink unchanged, which suits tabular to tabular and
blob to blob.

`wait_for_terminal` returns a `FAILED` pipeline rather than raising on it: a failure is a result to read. It does
raise on a timeout, and on any API or transport error from the polls it makes underneath. The `timeout` argument is
a hard, finite budget that also bounds each poll request in flight. The go-client differs here: there the context
owns cancellation and `timeout <= 0` means "no SDK deadline of its own".

The pipeline moves through `SUBMITTED`, `PROVISIONING`, `RUNNING`, then `COMPLETED`, `FAILED` or `CANCELLED`. On
failure, `pipeline.status_details.failed_stage` names the stage that failed: source, step, sink or runner. For a step,
`pipeline.failed_step_index` is the index into `steps` of the one that failed (`None` for any other stage).
`status_details` is a typed `PipelineStatusDetails` (a `ConnectionStatusDetails` on a connection): counters are `int`,
enum fields are members, and it can still be read as a mapping with `[]` or `.get()`. `pipeline.stats` is a shortcut for
`status_details.stats`, `pipeline.step_stats` lists each step's counters, and `pipeline.step_stage_ids` each step's
stage id (with `pipeline.source_stage_id` and `pipeline.sink_stage_id` for the other two). Stage ids are for support
requests and log searches; the pipeline API is how you manage a pipeline's stages.

A pipeline is immutable and has no `update`: create a new pipeline instead. `delete()` needs a terminal pipeline, so
`cancel()` first if the run is still live.

Full walk-through, including where step and runner memory are set: [examples/quickstart_pipeline.md](examples/quickstart_pipeline.md).

One runnable example per pipeline shape, each with its own walk-through:

| Example | Shape | What it covers beyond the basics |
|---|---|---|
| [quickstart_pipeline](examples/quickstart_pipeline.md) | postgres → S3, `processor-csv` step | the baseline flow: provisioning a step, watch, poll, cancel, cleanup |
| [quickstart_pipeline_parquet](examples/quickstart_pipeline_parquet.md) | postgres → S3, `processor-parquet` step | parquet config keys and the step worker's memory rule |
| [quickstart_pipeline_blob_to_blob](examples/quickstart_pipeline_blob_to_blob.md) | S3 → S3, no steps | server-side copy, the single-object rule, and content-type on a pass-through |
| [quickstart_pipeline_securestore](examples/quickstart_pipeline_securestore.md) | postgres → S3, `processor-csv` step | source and sink resolving credentials from SecureStore, plus depositing them |
| [quickstart_pipeline_h2odrive](examples/quickstart_pipeline_h2odrive.md) | postgres → H2O Drive | the four Drive auth modes and the STS token exchange |

## Low-level access

A session covers reads, writes, sync and previews. A test, a diagnostic or a tool that needs the wire itself uses
`session.transport`: the gRPC client the session talks to its worker with, built on first access, shared with the
session's own calls and closed by `session.close()`. `h2o_connector_service.transport` holds its class, `WorkerClient`,
`resolve_worker_target()` for the address of a connection's worker, and the protobuf messages a hand-built batch needs;
the whole generated surface is under `h2o_connector_service.gen`.

```py
from h2o_connector_service import encode_value
from h2o_connector_service.gen.data_pb2 import DATA_TYPE_INT64, DATA_TYPE_STRING, SCHEMA_FORMAT_FIELDS
from h2o_connector_service.transport import (
    Field, FieldSchema, Record, RecordBatch, RecordValues, Schema, TabularTarget, WriteBatch, WriteConfig, WriteMode,
)

with client.open_session(connector="pg-prod", worker="w-pg", direction=Direction.WRITE, write=write) as session:
    # The schema names the columns the values go to; without it a worker names them field_0, field_1
    # and the target's columns stay empty.
    schema = Schema(
        format=SCHEMA_FORMAT_FIELDS,
        field_schema=FieldSchema(fields=[Field(name="id", type=DATA_TYPE_INT64), Field(name="name", type=DATA_TYPE_STRING)]),
    )
    config = WriteConfig(tabular=TabularTarget(target_table="public.t"), mode=WriteMode.WRITE_MODE_INSERT, schema=schema)
    row = Record(values=RecordValues(values=[encode_value(1), encode_value("a")]))
    batch = WriteBatch(sequence_number=0, records=RecordBatch(records=[row]))
    for response in session.transport.stream_write(session.connection.connection_id, config, [batch]):
        print(response)  # a WriteAck per batch, then the WriteComplete with its status_details
```

Use the transport from the thread that owns the session, one operation at a time, and consume a stream before the
session closes. Do not close it yourself: `WorkerClient.close()` ends any RPC in flight and the client refuses every
later call, and the session has no other. Closing the session from another thread while a read is running ends
that read; the reader gets a `SessionError`. A read through the transport is not tracked by the session and still uses
the connection's one read. `get_schema()` returns the protobuf `Schema` where `session.schema()` returns the model,
and both need a read session (a worker refuses a write token on that call);
every call raises this package's exceptions for a failed RPC, never `grpc.RpcError`. `stream_data()`, `get_schema()` and
`stream_write()` take `timeout=` (seconds, a `timedelta` or `"30s"`) for the whole call, retries included, and raise
`DeadlineExceeded` past it (an HTTP call already in flight, such as a token refresh or an endpoint lookup after
UNAVAILABLE, finishes first); without one a call is unbounded, as a long read
needs. For an RPC the client does not wrap,
build the stub on `session.transport.channel` and pass `session.transport.call_metadata()` with each call; such a call
gets none of the client's retry, mapping or timeout. This surface is provisional in 0.4: a minor release may change it.

## Migrating from 0.3

0.4 changes the API in several places. Each line shows the 0.3 form, then the 0.4 form.

Client

- Constructor names: `Client(h2o_cloud_url=url, refresh_token=tok, ssl_cacert=ca)` becomes
  `Client(environment=url, platform_token=tok, ssl_ca_cert=ca)`. The old names still work with a `DeprecationWarning`.
- `Client()` with nothing set used to raise at once; it now reads the H2O CLI config first, then raises
  `ValidationError`.
- Client-side argument errors: `except ValueError` / `ConnectorServiceError(status_code=None)` becomes
  `except ValidationError` (still a `ValueError`). Server errors are subclasses such as `NotFound`; checking
  `e.status_code == 404` still works.

Resources

- Metadata: `client.connectors.create(ws, metadata={"name": "pg", "display_name": "PG"}, ...)` becomes
  `client.connectors.create(ws, name="pg", display_name="PG", ...)`. The same holds for `update()` and every resource.
- Unknown keywords: `create(ws, some_new_field=...)` becomes `create(ws, ..., extra={"some_new_field": ...})`.
- `client.connections.update(...)`, `client.pipelines.update(...)` and `data_source_profiles` create, update and delete
  are removed.
- `status_details["stats"]["unitsProcessed"]` (a string) becomes `status_details.stats.units_processed` (an `int`); mapping
  access still works. Duration fields read back as `timedelta` instead of `"3600s"`.
- `WriteMode` values are the canonical proto names (`WriteMode.UPSERT.value == "WRITE_MODE_UPSERT"`); every mode
  argument accepts the member, `"UPSERT"` or `"WRITE_MODE_UPSERT"`.

Reading

- Values: timestamps were microsecond integers and are now UTC `datetime`; dates, times and decimals are `date`,
  `time` and `Decimal` instead of integers or strings. See [Values](#values).
- `session.get_schema()` (a dict of column name to type name) becomes `session.schema()`, which returns a typed
  `Schema`.
- `session.stream_records(max_batches=10)` becomes `session.stream_records(limit=1000)`, counted in rows; the same
  for `stream_to_csv`, `stream_to_pandas` and the other `stream_to_*` outputs. `stream_to_files(max_batches=...)`
  becomes `stream_to_files(max_objects=...)`.
- Columns of a source with no schema: `col_0`, `col_1` become `column_1`, `column_2`.
- A second `stream_*` call on one session now raises `SessionError`; open a new session to read again.
- `from h2o_connector_service._session import _extract_value` becomes `from h2o_connector_service import decode_value`,
  and `_value_from_python` becomes `encode_value`.

Writing

- `client.open_write_session("postgresql", cfg, workspace_id=ws, target_table="t")` becomes
  `client.provision_session("postgresql", cfg, workspace_id=ws, direction=Direction.WRITE,
  write={"tabular": {"target_table": "t"}})`.
- `client.open_blob_write_session("s3", cfg, workspace_id=ws, target_url="out.csv")` becomes
  `client.provision_session("s3", cfg, workspace_id=ws, direction=Direction.WRITE, write={"blob": {"target_url": "out.csv"}})`.
- `open_session(..., direction=Direction.WRITE)` takes `write=` with the target and mode; the write calls use it as
  their defaults.
- `result.total_rows_written` becomes `result.rows_written` for records and `result.bytes_written` for blob writes.

Python 3.11 is now the minimum version.

## Optional dependencies

Install extras for the output formats you need:

```bash
pip install h2o-connector-service[pandas]       # pandas DataFrames
pip install h2o-connector-service[parquet]      # Parquet files (pyarrow)
pip install h2o-connector-service[datatable]    # datatable Frames
pip install h2o-connector-service[h2o]          # H2O Frames (pandas + pyarrow + h2o)
```
