> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lancedb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Secrets with Python Functions

> Create, bind, grant, alter, and drop a Secret from Python, and diagnose registration and refresh failures.

Enterprise only

A Function binds a [Secret](https://docs.lancedb.com/oss/v0-42-1/management/secret.md) by name. Its credential is
resolved when a job uses the Function, so altering the Secret does not require
registering another Function version.

## Connect and create a Secret

Use an Enterprise database with Functions enabled and a configured
[Secrets encryption key](https://docs.lancedb.com/oss/v0-42-1/enterprise/deployment/kms). The deployment operator
sets `global.secretsKmsKeyId` and grants the query nodes and execution services
access to that key. Without a sealing key, Secret operations are unavailable;
there is no plaintext fallback. Secrets also require a native manifest-backed
database. In this SDK, the Secret lifecycle uses Flight SQL, including its
error channel (gRPC `UNIMPLEMENTED`, code 12, for an unavailable feature).

Install the SDK and the client dependency used by this example:

```bash theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
python -m pip install --extra-index-url https://pypi.fury.io/lancedb/ "lancedb==0.42.0b38" openai
```

Set `LANCEDB_DATABASE`, `LANCEDB_ENDPOINT` (the HTTP or HTTPS REST URL),
`LANCEDB_SQL_ENDPOINT` (the corresponding Flight SQL URL), `LANCEDB_API_KEY`,
and `OPENAI_API_KEY` in your environment. For example, use
`grpc://your-sql-host:10025` for plaintext or
`grpc+tls://your-sql-host:10026` for TLS, as configured by your operator.
Supply the SQL endpoint explicitly, especially for HTTPS REST endpoints.
Run the Python
examples in a notebook or a file so that the SDK can inspect the Function's
source. Use a disposable database or keep the generated names for cleanup.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
import os
from uuid import uuid4

import lancedb
import pyarrow as pa
from lancedb import EnvVarSecret, col, function
from lancedb.authz import Object, Privilege, Subject
from lancedb.exceptions import JobFailedError
from lancedb.remote.errors import HttpError, SqlError
from openai import OpenAI

database_name = os.environ["LANCEDB_DATABASE"]
db = lancedb.connect(
    f"db://{database_name}",
    api_key=os.environ["LANCEDB_API_KEY"],
    host_override=os.environ["LANCEDB_ENDPOINT"],
    sql_host_override=os.environ["LANCEDB_SQL_ENDPOINT"],
)
run_id = uuid4().hex
secret_name = f"embedding_key_{run_id}"
table_name = f"secret_documents_{run_id}"

db.create_secret(secret_name, os.environ["OPENAI_API_KEY"])
```

Run the lifecycle and missing-Secret checks as a database/namespace owner.
To delegate creation instead, a caller needs database and namespace `USAGE`,
plus `CREATE_SECRET`, `CREATE_FUNCTION`, and `CREATE_TABLE` on the namespace.
Using an existing Secret also requires `USAGE` on that Secret. The creator owns
each new object. These examples use the root namespace; for another namespace,
pass the same `namespace_path` to object operations and
`secret_namespace_path` to `EnvVarSecret`.

## Register, bind, and refresh

Declare the remote dependency on the Function as well as installing it in the
client environment. The class reads the credential in `__init__`, once per
remote instance, and never returns it.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
@function(name=f"embed_remote_{run_id}", pip=["openai"])
class EmbedRemote:
    def __init__(self):
        self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

    def __call__(self, text: str) -> list[float]:
        response = self.client.embeddings.create(
            input=text, model="text-embedding-3-small"
        )
        return response.data[0].embedding


embed_function = db.create_function_async(
    EmbedRemote,
    secrets=[EnvVarSecret(secret_name=secret_name, env_variable="OPENAI_API_KEY")],
).wait()

input_schema = pa.schema([pa.field("text", pa.string(), nullable=False)])
table = db.create_table(
    table_name,
    data=pa.Table.from_pylist([{"text": "A document to embed"}], schema=input_schema),
)
table.add_columns(
    {"embedding": embed_function(text=col("text"))},
    auto_refresh_enabled=False,
)
refresh = table.refresh_column_async("embedding").wait()
assert refresh.rows_failed == 0
assert refresh.rows_remaining == 0
table.checkout_latest()
assert table.count_rows("embedding IS NULL") == 0
```

Registration validates binding shape: variable syntax, reserved names, and
duplicate variables. It does not resolve the Secret. `add_columns` validates
that the bound Secret exists; refresh admission checks it again and authorizes
the caller. Declaring the column does not fill its rows. Remote tables require
`refresh_column_async(...).wait()`; synchronous `refresh_column` raises
`NotImplementedError` in this SDK.

Adding a Function column requires table `OWNERSHIP`. Refreshing an existing
binding requires table `UPDATE`. Both operations also require Function and
Secret `USAGE`.

## Grant and revoke access from Python

A second caller needs `USAGE` on both the Function and every bound Secret.
Use the catalog's authorization API from an account that owns those objects.
Replace `secret_refreshers` with an existing role assigned to the second
caller. This example also grants database/namespace access and table read and
update privileges so the role can refresh and inspect the existing column.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
catalog = lancedb.connect_catalog(
    os.environ["LANCEDB_ENDPOINT"], api_key=os.environ["LANCEDB_API_KEY"]
)
subject = Subject.role("secret_refreshers")
secret_object = Object.secret(database=database_name, name=secret_name)
function_object = Object.function(database=database_name, name=embed_function.name)
table_object = Object.table(database=database_name, name=table_name)

grants = [
    (Object.database(database_name), Privilege.USAGE),
    (Object.namespace(database=database_name), Privilege.USAGE),
    (table_object, Privilege.SELECT),
    (table_object, Privilege.UPDATE),
    (function_object, Privilege.USAGE),
    (secret_object, Privilege.USAGE),
]
for resource, privilege in grants:
    catalog.authz.add_acl(object=resource, subject=subject, privilege=privilege)
```

`add_acl` returns HTTP 409 if that exact grant already exists. Inspect
`catalog.authz.list_acls(object=secret_object)` when sharing existing objects.
For a nested namespace, pass its path to the `Object` builders too.

Revoke just Secret usage, leaving Function and table access in place:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
catalog.authz.delete_acl(
    object=secret_object, subject=subject, privilege=Privilege.USAGE
)
```

A new refresh under the second caller's credentials is now refused with HTTP
403\. Regrant Secret usage to allow it again. Perform this check with the
second caller's connection: the owner's connection retains ownership and
will still succeed. Reading already filled rows requires only table `SELECT`
and database/namespace access; it does not invoke the Function.

On deployments that expose SQL grants, the Python SDK can also run
`db.execute_query("GRANT USAGE ON SECRET ... TO ROLE ...").read_all()` and
the corresponding `REVOKE`. See [privileges](https://docs.lancedb.com/oss/v0-42-1/governance/privileges.md) for the
operation matrix and [grant syntax](https://docs.lancedb.com/oss/v0-42-1/sql/ddl/grant.md) for quoting object names.

## Alter, refresh new work, and drop

Set `OPENAI_API_KEY_NEXT` to a replacement provider key. Alter the existing
Secret, then add an unfilled row so the next refresh has work to perform:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
db.alter_secret(secret_name, os.environ["OPENAI_API_KEY_NEXT"])
table.add(
    pa.Table.from_pylist([{"text": "A document after alteration"}], schema=input_schema)
)
refresh = table.refresh_column_async("embedding").wait()
assert refresh.rows_assigned > 0
assert refresh.rows_failed == 0
assert refresh.rows_remaining == 0
```

The same Function version and column binding use the new value for the next
job. Altering the Secret does not invalidate already computed rows. Running jobs
and their retries keep their captured values. `UPDATE` on the Secret permits
altering its value; `OWNERSHIP` permits dropping it.

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
db.drop_secret(secret_name)
```

Dropping removes the Secret and its grants. It leaves the Function and column
binding in place, so their next refresh fails. Running jobs retain their
captured values. To stop provider calls immediately, revoke the key at the
provider. Recreating the Secret under the same name supplies future jobs
with the replacement value, but does not restore the deleted grants.

## Observe a missing Secret at column use

After the drop above, registering another Function version with the same
binding still succeeds. Adding a column using it fails before row execution:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
late_function = db.create_function_async(
    EmbedRemote,
    secrets=[EnvVarSecret(secret_name=secret_name, env_variable="OPENAI_API_KEY")],
).wait()
late_table = db.create_table(
    f"late_secret_{run_id}",
    data=pa.Table.from_pylist([{"text": "Missing credential"}], schema=input_schema),
)
try:
    late_table.add_columns(
        {"embedding": late_function(text=col("text"))},
        auto_refresh_enabled=False,
    )
except HttpError as exc:
    assert exc.status_code == 400
    print("Missing bound Secret:", secret_name, "request:", exc.request_id)
else:
    raise AssertionError("Expected the missing Secret to reject column creation")
```

`table.refresh_column_async("embedding")` on the original table fails at admission
for the same reason. The error identifies the missing Secret and its bound
variable. An owner is used here so a missing `USAGE` grant does not mask the
missing-object check.

## Handle Python errors

The SDK uses two transports. Secret creation, alteration, description, listing,
and drop use Flight SQL. General SQL failures raise
`lancedb.remote.errors.SqlError`, with `grpc_code` and no HTTP status. When the
server includes structured resource metadata, this SDK maps SQL `not_found`
and `already_exists` errors to `SecretNotFoundError` and `AlreadyExistsError`
(both `HttpError` subclasses), with mapped HTTP statuses. A terminal query
failure can instead raise `lancedb.exceptions.JobFailedError`, with either
kind of structured error in `__cause__` when available. Keep the job/request
IDs when no structured cause exists.

Function registration, column declaration, refresh submission, and catalog ACL
calls use REST. Catch `HttpError` and inspect `status_code` for these requests.
After a refresh is admitted, a failed `.wait()` raises `JobFailedError`.

| Operation or failure | Python exception / code | Action |
| - | - | - |
| Create a Secret whose name is taken | `AlreadyExistsError` / mapped 409 with resource metadata; otherwise `SqlError` / gRPC 6 (`ALREADY_EXISTS`); possibly wrapped in `JobFailedError` | Choose another name or deliberately alter with `alter_secret` |
| Describe or alter a missing Secret | `SecretNotFoundError` / mapped 404 with resource metadata; otherwise `SqlError` / gRPC 5 (`NOT_FOUND`); possibly wrapped in `JobFailedError` | Check the name and namespace |
| Missing privilege during Secret lifecycle calls | `SqlError`, gRPC 7 (`PERMISSION_DENIED`), or a terminal `JobFailedError` | Grant the required privilege to the acting caller |
| Secrets unavailable, including an unconfigured sealing key | `SqlError`, gRPC 12 (`UNIMPLEMENTED`), or a terminal `JobFailedError` | Ask the operator to configure KMS and a native manifest-backed database |
| Use a Function whose bound Secret is missing | `HttpError`, HTTP 400 at `add_columns` or refresh admission | Create the Secret or correct the binding |
| Missing Function, Secret, or table privilege at column declaration/refresh admission | `HttpError`, HTTP 403 | Grant the required privilege to the acting caller |
| Malformed local `EnvVarSecret` name or variable | `ValueError` (or `TypeError` for the wrong Python type) | Correct the binding before registration |
| Missing Flight SQL endpoint for an HTTPS REST endpoint | `ValueError` | Set `sql_host_override` to the deployment's SQL URL |
| Reserved or repeated environment variable at registration | `HttpError`, HTTP 400 | Use a valid, unreserved, unique variable |
| A submitted Function or refresh job fails | `lancedb.exceptions.JobFailedError` from `.wait()` | Inspect the job failure; admission succeeded but execution did not |

For example, recreate the Secret dropped above, attaching an actionable
explanation to an unavailable-feature failure. A duplicate name still fails
without overwriting a credential:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
try:
    db.create_secret(secret_name, os.environ["OPENAI_API_KEY"])
except (SqlError, HttpError, JobFailedError) as exc:
    cause = exc
    while cause is not None and not isinstance(cause, SqlError):
        cause = cause.__cause__
    if isinstance(cause, SqlError) and cause.grpc_code == 12:
        raise RuntimeError("Ask the operator to enable Secrets with a KMS key") from exc
    raise
```

Catch refresh admission errors at submission and execution failures while
waiting on the returned handle:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
try:
    refresh_job = table.refresh_column_async("embedding")
except HttpError as exc:
    print("Refresh rejected:", exc.status_code, exc.request_id)
    raise

try:
    refresh = refresh_job.wait()
except JobFailedError as exc:
    print("Refresh failed:", exc.job_id)
    raise
```

Recreate the dropped Secret with the lifecycle handler above before running
this refresh. Catching only `HttpError` misses general SQL lifecycle failures.
In particular, an unavailable feature uses gRPC 12 rather than an HTTP 501
exception from these Python methods.

## Reserved environment variables

Names are case-sensitive. The complete reserved exact names are:

```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
HOME PATH TEMP TMP TMPDIR LANG LC_ALL LC_CTYPE TZ
HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy
SSL_CERT_FILE SSL_CERT_DIR REQUESTS_CA_BUNDLE
PYTHONHOME PYTHONPATH PYTHONDONTWRITEBYTECODE
LD_LIBRARY_PATH LD_PRELOAD DYLD_LIBRARY_PATH DYLD_INSERT_LIBRARIES
UV_CACHE_DIR UV_NATIVE_TLS UV_PYTHON_INSTALL_DIR RUST_BACKTRACE
```

Every name starting with one of these prefixes is also reserved:

```text theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
DYLD_ INDEXER_ LANCE_ LANCEDB_ LD_ PYTHON SOPHON_
```

Other variable names must match `[A-Za-z_][A-Za-z0-9_]*`. A Function can bind
at most 16 Secrets, with each environment variable bound once.

## Clean up the example

After finishing the missing-Secret checks, drop the disposable tables and
Function, then drop the Secret recreated in the error-handling example:

```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
db.drop_table(f"late_secret_{run_id}")
db.drop_table(table_name)
db.drop_function(embed_function.name, version=embed_function.version)
db.drop_secret(secret_name)
```

Review and remove any database or namespace grants added solely for this
example. See [Secret management](https://docs.lancedb.com/oss/v0-42-1/management/secret.md) and
[Secret delivery](https://docs.lancedb.com/oss/v0-42-1/curation/vend-secret.md) for the lifecycle guarantees.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.