中文 | English
Python SDK for writing, querying, and managing agent trajectory data on the Wind Tunnel data platform. All database operations use dldb, which manages logical partitions on top of LanceDB.
dldb is installed from the public
DeepLink-org/Persisting repository
at the dldb-v1.1.7 tag declared in pyproject.toml. This version is required
for exact logical-table resolution and unpartitioned SimpleTable reopening.
The supported Python versions are 3.10 through 3.12.
python -m pip install -e .
python -m pip install -e ".[etl]" # Core SDK plus ETL-only dependencies
python -m pip install -e ".[dev,etl]" # Full repository developmentThe ETL subsystem is isolated under wt_sdk/etl/. Core SDK imports never load
it. Install ETL-specific dependencies only when needed:
ETL v1 currently adds no third-party packages beyond the core SDK stack; the extra is the required boundary for future ETL-only dependencies.
The SDK reads process environment variables when a client is created. Existing application code can keep using WTGatewayClient().
Copy .env.example into the integrating service as .env, replace the placeholders, and keep the real file out of version control.
# .env
# Optional: landing/env-config live on a local (GPFS) path, serving on S3.
# Unset, they default to the platform's split-stack locations.
WT_SDK_LANDING_DB_URI=/mnt/shared-storage-user/adpc-share/wt-data-platform/landing
WT_SDK_SERVING_DB_URI=s3://wt-data-platform
WT_SDK_ENV_CONFIG_DB_URI=/mnt/shared-storage-user/adpc-share/wt-data-platform/env-config
WT_SDK_S3_ENDPOINT=http://your-s3-endpoint:8060
WT_SDK_S3_ALLOW_HTTP=true
AWS_ACCESS_KEY_ID=replace-with-your-access-key
AWS_SECRET_ACCESS_KEY=replace-with-your-secret-key
AWS_EC2_METADATA_DISABLED=true
WT_SDK_PROFILE=testLoad it before starting the application:
set -a && source .env && set +a
python your_service.pyFor CI, systemd, Kubernetes, or another deployment system, inject the same variables directly:
export WT_SDK_LANDING_DB_URI=/mnt/shared-storage-user/adpc-share/wt-data-platform/landing
export WT_SDK_SERVING_DB_URI=s3://wt-data-platform
export WT_SDK_ENV_CONFIG_DB_URI=/mnt/shared-storage-user/adpc-share/wt-data-platform/env-config
export WT_SDK_S3_ENDPOINT=http://your-s3-endpoint:8060
export WT_SDK_S3_ALLOW_HTTP=true
export AWS_ACCESS_KEY_ID=replace-with-your-access-key
export AWS_SECRET_ACCESS_KEY=replace-with-your-secret-key
export AWS_EC2_METADATA_DISABLED=true
export WT_SDK_PROFILE=test
python your_service.pyDocker Compose can reuse the same .env:
services:
app:
env_file:
- .envRead-only gateways and delivery exporters that never access landing can opt in to a single serving connection:
from wt_sdk import GatewayConfig, TableConfig, WTGatewayClient
config = GatewayConfig(
tables=TableConfig(profile="production"),
serving_only=True,
)
client = WTGatewayClient(config)This mode connects only to WT_SDK_SERVING_DB_URI (or its explicit/default
value), so the process needs S3 access but no GPFS mount or landing connection.
Any attempt to access a landing table raises RuntimeError instead of opening
a fallback connection. The delivery export and dataset-count scripts enable
this mode automatically.
The default is serving_only=False: existing clients still eagerly connect to
both landing and serving, including the existing shared-session behavior when
both roles use the same database URI.
WT_SDK_PROFILE selects default logical tables. Explicit GatewayConfig
values and method arguments such as search(table="...") take precedence.
| Profile | Landing table | Serving table | Environment-config table | ETL checkpoint table (only when ETL runs) |
|---|---|---|---|---|
test or omitted |
landing_test |
serving_test |
env_test |
etl_checkpoints_test |
production or prod |
wt_landing |
wt_serving |
wt_env_config |
wind_tunnel_etl_checkpoints |
Omitting WT_SDK_PROFILE safely defaults to test. Production access must be
selected explicitly with production or prod.
The checkpoint table is stored in a separate ETL database. Only checkpoint
initialization and default incremental ETL require either
WT_SDK_ETL_STATE_DB_URI=s3://wind-tunnel-etl or the ETL command's
--state-db-uri option. Ordinary SDK clients, upstream writers, and targeted
manual ETL by job/session/time/filter do not require or read this setting.
Missing it does not affect WT_SDK_PROFILE resolution. When the ETL state
database is used, the same profile selects the checkpoint table shown above.
EnvConfigManager uses the separate WT_SDK_ENV_CONFIG_DB_URI database. The
same profile selects env_test or wt_env_config; an explicit
table_name= overrides the profile, and an explicit db_uri= overrides the
environment-config database URI. The endpoint and AWS credentials above are
shared by both databases.
Environment-config reads use checkout_latest=True by default so a long-lived
process can see configs committed by another process after it started.
The default is backward-compatible with existing callers; pass
checkout_latest=False only when an older snapshot is intentionally acceptable.
The following workflow models one agent evaluation job from raw trajectory capture to training consumption and searchable serving data. Load credentials and the table profile through environment variables, then reuse one client within each process.
Use ingest_landing() for an event that must be persisted immediately and
ingest_landing_batch() for buffered events. Generate id and created_at
upstream; keep step_id unique and increasing within a session.
import json
import time
import uuid
from wt_sdk import LandingRecord, WTGatewayClient
def message(role: str, text: str) -> dict:
return {"role": role, "content": text}
job_id = "evaluation-run-001" # One evaluation run; the user-visible task id.
# (Landing partitions on sub_job_id, which the
# SDK auto-sets to job_id for non-split jobs.)
session_id = str(uuid.uuid4()) # One agent trajectory
created_at = int(time.time())
def make_record(step_id: int, terminal: bool = False) -> LandingRecord:
return LandingRecord(
id=f"{session_id}:{step_id}", # Caller-provided and globally unique
dataset_type="RL",
job_id=job_id,
session_id=session_id,
step_id=step_id,
created_at=created_at + step_id,
is_terminal=terminal,
is_session_completed=terminal,
# Trajectory payload columns are opaque JSON strings at the SDK boundary.
messages=json.dumps([message("user", f"task input for step {step_id}")]),
response=json.dumps(message("assistant", f"result for step {step_id}")),
meta_json=json.dumps(
{"task_id": "benchmark-task-42", "group_id": "group-a"}
),
)
first = make_record(1)
buffered = [make_record(2), make_record(3, terminal=True)]
scope = f"job_id = '{job_id}' AND session_id = '{session_id}'"
with WTGatewayClient() as client:
client.ingest_landing(first) # Low-latency single write
client.ingest_landing_batch(buffered) # Higher-throughput buffered write
# Reward may arrive after the terminal event has been stored.
client.update_landing(
f"{scope} AND step_id = 3",
{"reward": 1.0, "step_reward": 1.0, "is_trainable": True},
) # source_updated_at is refreshed automatically.
trajectory = client.query_data(
scope,
order_by="step_id",
checkout_latest=True,
exclude_none=True, # Default: omit null table columns from each result.
deserialize_json=True, # Return JSON columns as dict/list values.
)
first_step_id = trajectory[0]["step_id"] # query_data() returns List[dict].
# Landing partitions on sub_job_id; non-split jobs self-reference job_id,
# so job_id doubles as the partition value here.
job_row_count = client.count_landing(partition=job_id)
# Prefer this pruned lookup when both job_id and id are known.
exact_event = client.query_data(
f"job_id = '{job_id}' AND id = '{buffered[-1].id}'",
limit=1,
)query_data() returns plain dictionaries and omits null table columns by
default; pass exclude_none=False when a complete schema-shaped payload is
required. JSON columns remain JSON strings by default and are never modified by
exclude_none; pass deserialize_json=True to return their documents as Python
dict/list values. Deserialization does not remove nulls inside JSON.
deserialize_json=False # LanceDB-native output: JSON strings (default).
deserialize_json=True # SDK applies json.loads(): Python dict/list values.messages, response, chosen_trace, rejected_trace, and meta_json use
Arrow json<string> in both landing and serving. Callers serialize the entire
JSON document with json.dumps() before ingestion. A trace is therefore a JSON
array encoded as one string, not an Arrow list<struct>. The SDK deliberately
does not enforce an OpenAI or provider-specific document shape; landing may keep
provider-native raw data in meta_json, while ETL writes normalized OpenAI-style
payload JSON into serving.
| Field | Unit | Meaning |
|---|---|---|
created_at |
Existing caller-defined unit | Original trajectory creation time; immutable after ingestion. |
source_updated_at |
Unix epoch milliseconds | Last substantive source change that may affect ETL/serving output. Automatically initialized and refreshed by landing updates. |
serving_updated_at |
Unix epoch milliseconds | Last successful serving ingest/upsert publication. Always null in landing. |
Callers may provide source_updated_at when replaying or migrating records;
otherwise LandingRecord/ServingRecord initializes it. Serving writes preserve
that source value and stamp a fresh serving_updated_at on an internal copy, so
the caller's model is not mutated.
A long-running trainer pulls one page at a time and saves the cursor only after
that page is processed successfully. pull_data() adds the dataset_type
filter; keep job_id in where_sql for HASH pruning. The placeholder
load_checkpoint(), process_page(), and save_checkpoint() calls below belong
to the consuming application; scope each durable checkpoint by consumer and
query/table identity.
job_filter = "job_id = 'evaluation-run-001' AND is_terminal = True"
page_size = 1000
stored_cursor = load_checkpoint() # Return None when no checkpoint exists.
with WTGatewayClient() as client:
while True:
page = client.pull_data(
dataset_type="RL",
where_sql=job_filter,
cursor=stored_cursor,
limit=page_size,
checkout_latest=True,
deserialize_json=True,
)
if page.empty:
break
process_page(page)
next_cursor = client.extract_cursor(page)
save_checkpoint(next_cursor) # Persist only after processing succeeds.
stored_cursor = next_cursor
if len(page) < page_size:
break
# Optional: inspect the current high-water mark for this pull scope.
latest_record = client.get_max_created_at(
where_sql=f"dataset_type = 'RL' AND {job_filter}",
)get_max_created_at() is a cursor/watermark helper for pull_data() workflows,
not a separate data-retrieval mode. It is useful for initialization, monitoring,
or recovery checks; normal page advancement should still persist the cursor from
extract_cursor(page) only after the page is processed successfully.
For a convenient one-run scan or backfill, iter_data_batches() manages the
created_at cursor and yields DataFrame batches lazily:
with WTGatewayClient() as client:
for batch in client.iter_data_batches(
dataset_type="RL",
where_sql="job_id = 'evaluation-run-001'",
chunk_size=1000,
deserialize_json=True,
):
print(f"received {len(batch)} rows")pull_data() and iter_data_batches() keep landing as their default. External
consumers can pass table=client.config.tables.serving_table. Consumers that
need Python payload objects should also pass deserialize_json=True and handle
ordinary dict/list values rather than the former Arrow nested containers. Both
APIs use a created_at cursor, so they are not the formal export path when
multiple rows can share a timestamp.
After ETL or training selection, publish enriched records to serving. Landing and serving use the same schema; fields that have not been enriched yet remain null in landing. Vector search is not currently exposed.
from wt_sdk import ServingRecord
serving_data = buffered[-1].model_dump()
serving_data.update(
reward=1.0,
step_reward=1.0,
is_trainable=True,
search_text="benchmark task final successful response",
tags=["trainable", "successful"],
)
serving_record = ServingRecord(**serving_data)
with WTGatewayClient() as client:
# ETL publication should be retryable and race-free.
client.upsert_serving(serving_record)
published = client.get_by_id(
serving_record.id,
exclude_none=True,
deserialize_json=True,
)
assert published and published["id"] == serving_record.id
matches = client.search(
"successful",
dataset_type="RL",
tags=["trainable"],
limit=20,
deserialize_json=True,
)get_by_id() queries serving by default, or exactly the named table; it does
not fall back across the internal/external table boundary. Because an ID alone
cannot identify a HASH bucket, prefer query_data() with both job_id and id
on hot landing paths. Like query_data(), it returns a plain dictionary and
omits null table columns by default without modifying JSON strings.
ETL should publish complete records through upsert_serving() or
upsert_serving_batch(). These methods call dldb's native upsert path with
columns=["job_id", "id"] by default; pass match_columns= to override the
dldb merge keys when an explicit upstream key contract requires it. Do not
implement a query-then-ingest/update sequence. Repeated upserts converge to the
same business content, while serving_updated_at
records the most recent successful publication and may therefore change on a
retry. Every upsert record requires a non-empty, immutable job_id. dldb HASH
tables do not provide a uniqueness constraint across buckets, so callers should
keep IDs globally unique and must never move an existing ID to another job_id.
The append/add ingest_serving(_batch) methods remain available and
also stamp serving_updated_at.
For narrow patches that do not need to rewrite wide payload columns, pass
insert_missing=False to upsert_landing(), upsert_landing_batch(),
upsert_serving(), or upsert_serving_batch(). Existing matching rows are
patched in place; unmatched keys are ignored and new HASH buckets are not
created. All records in one batch must contain the same set of supplied fields.
An explicitly supplied None clears that field, while omitted fields retain
their existing values.
For landing, the SDK submits the supplied LandingRecord fields plus the match
columns, refreshed source_updated_at, and the sub_job_id routing column.
For serving, only explicitly supplied fields are patched, except that
created_at, dt, source_updated_at, and sub_job_id are protected (unless
one is explicitly used as a custom match key). The default match keys are
job_id + id; job_id is also retained for HASH routing. A caller-supplied
serving_updated_at is ignored: the SDK generates one publication timestamp
per batch and always submits it. Other supplied fields, including JSON strings
such as analysis and training_results, are submitted normally:
with WTGatewayClient() as client:
client.upsert_landing_batch(
reward_patches,
match_columns=("job_id", "id"),
insert_missing=False,
)
analysis_patch = ServingRecord(
dataset_type="RL",
id="serving-1",
job_id="evaluation-run-001",
created_at=0, # Required by the model; protected in serving partial mode.
analysis='{"score": 0.9}',
training_results='{"status": "complete"}',
)
client.upsert_serving(analysis_patch, insert_missing=False)The default remains insert_missing=True for backward compatibility: an
unmatched row is inserted and a matched row is replaced by the complete row.
ETL should keep this complete-row publication behavior. Partial updates do not
establish field ownership or protect fields from later complete-row writes: a
subsequent full-row ETL republish can still overwrite serving-only fields such
as analysis or training_results.
The repository now includes the ETL v1 engine, durable per-bucket checkpoints,
manual backfill modes, and the built-in chosen-trace/tag stages. Contributors
must follow the stage contract and integration guide in
wt_sdk/etl/README_STAGE_DEVELOPMENT.md;
runtime and operational guidance remains in
wt_sdk/etl/README.md.
List the registered pipelines without connecting to any database:
python -m wt_sdk.etl.cli.run --list-pipelinesFor a formal offline export after serving data has been published, use
export_data_batches(). It defaults to serving, captures a complete unique-ID
manifest before yielding the first batch, and then validates every exact-ID
batch. Rows appended after manifest capture are excluded; duplicate IDs or source
rows deleted/changed so they no longer match cause a hard failure instead of
silent loss:
export_data_batches() requires a Python runtime built with standard-library
sqlite3 support. No external SQLite service or additional pip package is
required.
with WTGatewayClient() as client:
for batch in client.export_data_batches(
filter_query="dataset_type = 'RL' AND is_trainable = True",
batch_size=5000,
columns=["id", "job_id", "chosen_trace", "tags", "meta_json"],
):
write_to_temporary_export(batch)
publish_completed_export()Treat serving rows selected for an export as immutable until iteration completes, and publish a file only after the iterator is exhausted successfully. dldb does not expose one atomic snapshot across all physical HASH buckets, so this manifest and validation protocol provides a stable row set but cannot preserve pre-update field values if a selected row is modified during export.
Do not build indexes in the synchronous writer path. After a job finishes, or from a background operations process, refresh only the bucket touched by that job:
with WTGatewayClient() as client:
summary = client.maintain_table_indexes(
"wt_landing",
partitions=["evaluation-run-001"],
)On landing the partitions values are sub_job_ids (hash buckets are derived
from them); a non-split job's single sub_job_id equals its job_id, so the value
above works as-is. For a split job pass each "{job_id}#{suffix}" shard id.
This creates missing configured indexes and runs dldb optimize so appended rows
enter existing indexes. Use all_partitions=True only for scheduled full-table
maintenance. The context manager closes the dldb session and emits its final
metrics summary when enabled.
| API | Accepted parameters | Return type | Pagination control | Default table | Best suited for |
|---|---|---|---|---|---|
query_data() |
filter_query, limit, columns, partition, order_by, ascending, checkout_latest, table, exclude_none, deserialize_json |
One List[dict] |
No cursor management; one query with optional limit |
Landing | Interactive filtering, trajectory/detail lookup, Dashboard lists, small bounded result sets |
get_by_id() |
record_id, table, exclude_none, deserialize_json |
One dict, or None |
None; scans the selected table because ID cannot locate a HASH bucket | Serving | Occasional lookup when only a globally unique ID is known |
pull_data() |
dataset_type, where_sql, start_time, end_time, cursor, order_by, ascending, limit, checkout_latest, table, deserialize_json |
One DataFrame page | Caller supplies, extracts, and persists the created_at cursor |
Landing | Incremental consumers, polling, retryable processing, durable checkpoints |
iter_data_batches() |
dataset_type, where_sql, start_time, end_time, chunk_size, order_by, ascending, table, deserialize_json |
Iterator yielding one DataFrame per batch | SDK advances the created_at cursor internally until exhausted |
Landing | Convenient one-run scans, backfills, and offline processing where timestamp ties are acceptable |
export_data_batches() |
filter_query, batch_size, columns, table, deserialize_json |
Iterator yielding one validated DataFrame per manifest batch | SDK first captures a complete unique-ID manifest, then fetches and verifies exact IDs | Serving | Formal offline exports requiring a fixed row set, duplicate-ID detection, and no timestamp-cursor gaps |
search() |
query, limit, tags, where_sql, dataset_type, stream, table, deserialize_json, checkout_latest |
One DataFrame, or a one-frame iterator with stream=True |
One bounded search | Serving | Dashboard keyword search over search_text, with tags and scalar filters; LIKE metacharacters are literal and latest snapshot is the default |
query_data(), pull_data(), and iter_data_batches() default to landing and
accept table=client.config.tables.serving_table. get_by_id(), search(), and
export_data_batches() default to serving. Include job_id in filters whenever
possible for HASH bucket pruning.
Job splitting: job_id always names the complete, user-visible task. Landing is
partitioned on the internal write shard sub_job_id — the SDK fills it with
job_id when a record omits it (non-split jobs self-reference their job_id);
split jobs write "{job_id}#{suffix}" shards registered in the env table's
sub_job_ids. The SDK rewrites job_id-only landing filters into
sub_job_id IN (shards) and prunes to those buckets; job_id remains the
partition key of serving. resolve_sub_jobs(job_id) exposes the shard list.
query_data() and get_by_id() omit null table columns by default. Pass
exclude_none=False to retain them. All row-returning read APIs keep JSON as
strings by default; deserialize_json=True returns Python values while
preserving JSON-internal nulls. Malformed JSON remains unchanged as a string so
a presentation option cannot make an otherwise readable row fail.
Within one WTGatewayClient lifetime, dldb 1.1.7 resolves the exact
information-schema record and reuses its logical-table wrapper and opened
physical bucket objects. The SDK does not reconstruct or pin dldb wrappers.
This applies to reads, writes, index maintenance, and scripts built on the
client; it does not cache query results or change checkout_latest. Code that
mutates the logical catalog through client.session_for(table_name) must call
client.invalidate_table_cache(table_name) before the next SDK operation.
| Method | Purpose |
|---|---|
| ingest_landing(record) | Write one LandingRecord. |
| ingest_landing_batch(records) | Write a list of records or LandingRecordBatch. |
| upsert_landing(record, *, match_columns=None, insert_missing=True) / upsert_landing_batch(records, *, match_columns=None, insert_missing=True) | Complete landing upsert by default; with insert_missing=False, patch only supplied fields on existing rows and ignore missing IDs. Defaults to job_id + id matching. |
| query_data(filter_query, ..., table=None, exclude_none=True, deserialize_json=False) | Query landing by default, or a named table; always return List[dict]. |
| update_landing(filter_query, updates, ..., touch_source_updated_at=True) | Patch matching rows and refresh source_updated_at by default. SDK timestamps, id, created_at, and job_id are protected. |
| count_landing(partition=None) | Count rows, optionally in one raw sub_job_id value or hash bucket. |
| delete_landing(filter_query) | Delete matching landing records. |
| resolve_sub_jobs(job_id) | List a job's write shards (sub_job_ids); non-split jobs return [job_id]. |
query_data() and update_landing() accept a raw partition value for compatibility; on landing it is a sub_job_id (job_id works for non-split jobs) and the SDK converts it to the bucket and adds a sub_job_id predicate. Prefer putting job_id in filter_query explicitly: the SDK expands it to the job's env-registered sub_job_ids and still prunes to exactly those buckets.
For an ordered or limited landing query, include job_id in filter_query. Cross-bucket order_by + limit is not a global merge sort in the current dldb partition model.
with WTGatewayClient() as client:
latest = client.query_data(
"job_id = 'job-001' AND session_id = 'session-001'",
order_by="step_id",
ascending=False,
limit=1,
)
result = client.update_landing(
"job_id = 'job-001' AND session_id = 'session-001' AND step_id = 1",
{"is_terminal": True, "is_trainable": True},
)Existing update_landing() calls require no changes: the new keyword-only
touch_source_updated_at defaults to True. Updates to is_trainable, payloads,
rewards, meta_json, agent_model, or any enrichment consumed by serving must
keep that default, including in-place landing ETL. Use
touch_source_updated_at=False only for a purely operational/diagnostic patch
that cannot affect any downstream result. The ETL engine should avoid calling
update when values did not actually change. update_landing() returns caller
fields in updated_fields and submitted fields in effective_updated_fields;
dldb does not yet return exact matched or updated counts across logical
partitions.
| Method | Purpose |
|---|---|
| ingest_serving(record) / ingest_serving_batch(records) | Append processed serving records and stamp serving_updated_at. |
| upsert_serving(record, *, match_columns=None, insert_missing=True) / upsert_serving_batch(records, *, match_columns=None, insert_missing=True) | Complete ETL publication by dldb match keys (default job_id + id); preserve source_updated_at and refresh serving_updated_at. With insert_missing=False, patch only supplied fields and ignore unmatched keys. |
| query_data(filter_query, ..., table=serving_table, exclude_none=True, deserialize_json=False) | Query serving with the same filtering and HASH pruning behavior; always return List[dict]. |
| count_serving(partition=None) / delete_serving(filter_query) | Operate on serving data. |
| search(query, ..., deserialize_json=False, checkout_latest=True, columns=None) | Search serving search_text, optionally constrained by tags/SQL filters; user %, _, and \\ characters are treated literally. Optionally project only list-view columns; the default returns complete rows. |
| get_tags_distribution() | Return serving tag frequencies. |
| get_by_id(record_id, table=None, exclude_none=True, deserialize_json=False, checkout_latest=False) | Return one compact dictionary from serving by default, or exactly one named table; long-lived readers can opt into the latest snapshot. |
| pull_data(..., table=None, deserialize_json=False) / iter_data_batches(..., table=None, deserialize_json=False) | Read landing by default, or a named table, with manual-page or automatic-batch iteration. |
| export_data_batches(filter_query="", ..., table=None, deserialize_json=False) | Reliably export a fixed ID manifest from serving by default; validates each exact-ID batch. |
Vector search is not currently exposed by dldb. Keyword search always targets
the ETL-generated search_text; tags, dataset type, and normal SQL conditions
remain available as filters. stream=True returns an iterator containing the
current result frame.
Environment configs live in the separate database selected by
WT_SDK_ENV_CONFIG_DB_URI. WT_SDK_PROFILE selects env_test for test
or wt_env_config for production. An explicit table_name= overrides
the profile. Read APIs default to checkout_latest=True so a long-lived gateway
process can see configs written by a launcher process after the gateway started.
from wt_sdk import EnvConfigManager
test_envs = EnvConfigManager() # test is the safe default
production_envs = EnvConfigManager(profile="production")
explicit_envs = EnvConfigManager(table_name="wt_env_config")Environment configs also support the optional string fields description,
primary_category, secondary_category, and env_meta_data, plus the nullable
boolean is_successed. They can be provided to save_config() /
upsert_config() and changed through the update APIs; get_env_configs() and
get_all_env_configs() return them. is_successed returns True, False, or
None when no success status has been recorded, and has a configured BTREE
index for filtering. In particular, env_meta_data is stored and returned as a
string, not automatically JSON-encoded or decoded like env_params.
| Method | Purpose |
|---|---|
get_env_configs(limit, offset=0, filter_query="", *, checkout_latest=True) |
Page through configs with an optional SQL filter. |
get_all_env_configs(*, checkout_latest=True) |
Return all configs sorted by id. |
get_env_image_map(*, checkout_latest=True) |
Build env_name -> image from the latest config table snapshot. |
get_all_image(*, checkout_latest=True) |
Build image -> env_name from rows with non-empty images. |
count(filter_query="", *, checkout_latest=True) |
Count configs, optionally matching a SQL filter. |
maintain_table_indexes() accepts one of the two production or two test table
names. The exact table name selects the landing or serving index definitions.
Callers must provide raw job IDs/HASH bucket integers or all_partitions=True;
the method creates missing indexes and runs dldb optimize by default.
For more frequent old-version cleanup with dldb>=1.1.11, --cleanup-only calls dldb
cleanup_old_versions() directly for each selected bucket. It skips index
inspection/creation, fragment compaction, index refreshes, coverage collection,
and full optimize():
# Clean only the landing bucket resolved from this sub_job_id/job_id
python scripts/ops/maintain_table_indexes.py \
--table wt_landing --partition job-123 \
--cleanup-only --cleanup-older-than-hours 24
# Clean only the serving bucket resolved from this job_id
python scripts/ops/maintain_table_indexes.py \
--table wt_serving --partition job-123 \
--cleanup-only --cleanup-older-than-hours 24Cleanup-only complements rather than replaces the daily full maintenance run:
the default command still creates missing indexes, compacts fragments, refreshes
indexes, and cleans old versions. Both modes require --partition (repeatable)
or --all-partitions and default to a 24-hour retention window.
The two HASH(job_id)-partitioned environment-config tables use their own
database and maintenance command. The default database URI is the GPFS
env-config path (/mnt/shared-storage-user/adpc-share/wt-data-platform/env-config),
overridden by WT_SDK_ENV_CONFIG_DB_URI or --db-uri. Inspect production
fragment and index health without modifying the table:
python scripts/inspect/show_env_config_status.py --profile production
python scripts/inspect/show_env_config_status.py --profile production --jsonThe report includes row/byte counts, fragment statistics, configured versus existing indexes, and indexed/unindexed row coverage. Run a read-only maintenance preview first, then create missing configured indexes and perform full table maintenance:
python scripts/ops/maintain_env_config_indexes.py --dry-run
python scripts/ops/maintain_env_config_indexes.py
python scripts/ops/maintain_env_config_indexes.py \
--profile production --dry-run
python scripts/ops/maintain_env_config_indexes.py \
--profile productionBy default the command calls dldb's full optimize(): it compacts fragments,
cleans old versions according to dldb's retention policy, and refreshes index
coverage. Use --no-optimize only when the operation should create missing
indexes without the full maintenance pass.
For old-version cleanup alone, preview the targets and then run cleanup-only:
python scripts/ops/maintain_env_config_indexes.py \
--profile production --cleanup-only --dry-run
python scripts/ops/maintain_env_config_indexes.py \
--profile production --cleanup-only --cleanup-older-than-hours 24The env command automatically cleans every materialized HASH bucket, or the
whole table for a legacy unpartitioned table. Its cleanup-only mode does not
inspect/create indexes, collect coverage, or run full optimize(); dry-run only
reports those targets and does not write to the database.
WT_SDK_DLDB_MODEL=metrics
WT_SDK_LOG_DLDB_TIMING=1
WT_SDK_DLDB_METRICS_LOG=./wt_metrics_log.jsonlIn metrics mode, client.close() returns the dldb session summary and appends per-call events plus a summary event to the configured JSONL file.
Unit tests use fakes and do not connect to S3 or dldb:
pytest -qThe timing test writes a readable JSONL example to the ignored
tests/artifacts/metrics_log.txt.
Integration tests write a few uniquely scoped rows to the landing_test and
serving_test tables, then clean and verify them in finally. They target
these explicit test tables independently of WT_SDK_PROFILE; each role uses its
own database (landing on GPFS, serving on S3 s3://wt-data-platform). Both
tables must use the current schema: landing is HASH(sub_job_id) and serving
is HASH(job_id).
set -a && source .env && set +a
WT_SDK_RUN_INTEGRATION=1 python -m pytest -q tests/integration
# ETL-only real integration tests
WT_SDK_RUN_INTEGRATION=1 python -m pytest -q wt_sdk/etl/tests/integrationWT_SDK_RUN_INTEGRATION=1 is a pytest safety switch, not an SDK runtime setting.
Load the same .env before running scripts:
set -a && source .env && set +a# List logical tables
python scripts/ops/table_manager.py list
# List another dldb database
python scripts/ops/table_manager.py list --db-uri s3://my-dldb-bucket
# Inspect schema, partition metadata, and scalar indexes
python scripts/ops/table_manager.py show-schema wt_landing
# List physical dldb/Lance tables behind a logical table
python scripts/ops/table_manager.py show-physical landing_test
# Inspect the production environment-config table
python scripts/ops/table_manager.py show-schema wt_env_config \
--db-uri "$WT_SDK_ENV_CONFIG_DB_URI"
# Environment-config initialization defaults to the test profile and is destructive
python scripts/ops/init_evaluation_env_table.py --dry-run
python scripts/ops/init_evaluation_env_table.py --confirm-recreate
# Production requires an explicit profile as well as destructive confirmation
python scripts/ops/init_evaluation_env_table.py \
--profile production --dry-run
# Interactive delete: type the exact table name, then DROP
python scripts/ops/table_manager.py drop landing_test
# Non-interactive delete: repeat the exact target
python scripts/ops/table_manager.py drop landing_test \
--force --confirm-table landing_test
# Delete one HASH bucket from a disposable test table
python scripts/ops/table_manager.py drop serving_test --partition 42--query accepts a standard SQL WHERE predicate without the leading
WHERE. Use normal SQL operators such as =, IN (...), LIKE, AND,
OR, comparison operators, and boolean literals. Wrap the whole predicate in
shell quotes so spaces and % patterns are passed to the script unchanged.
For the four active landing/serving tables, exact job_id = '...' predicates
use SDK HASH bucket pruning. Filtered queries and filtered --count do not
compute the full table size by default; add --with-total-count only when you
really need that slower full-table count.
Use --distinct to list unique values or unique column combinations; it reads
only the selected columns and computes uniqueness in the script.
# Count rows
python scripts/inspect/query_data.py --table wt_landing --count
# Count one exact job_id using HASH bucket pruning
python scripts/inspect/query_data.py --table wt_landing \
--query "job_id = 'job-001'" --count
# List all distinct job IDs and their count
python scripts/inspect/query_data.py --table wt_landing \
--distinct job_id
# Count distinct sessions inside one job without printing every value
python scripts/inspect/query_data.py --table wt_landing \
--query "job_id = 'job-001'" \
--distinct session_id \
--count
# List distinct job/session combinations and dump them to JSON
python scripts/inspect/query_data.py --table wt_landing \
--query "job_id LIKE '%panjia%'" \
--distinct "job_id,session_id" \
--output ./artifacts/panjia_distinct_sessions.json
# Query the test environment-config table; both env table names automatically
# use WT_SDK_ENV_CONFIG_DB_URI
python scripts/inspect/query_data.py --table env_test \
--query "job_id = 'job-001'" \
--columns "id,job_id,env_id,env_name,group_id,finished" \
--limit 20
# Count production environment configs for one job
python scripts/inspect/query_data.py --table wt_env_config \
--query "job_id = 'job-001'" --count
# Dump environment configs to a local JSON file
python scripts/inspect/query_data.py --table wt_env_config \
--query "job_id = 'job-001'" \
--output ./artifacts/job_001_env_configs.json
# Query selected columns
python scripts/inspect/query_data.py --table landing_test \
--query "job_id = 'job-001'" --columns "id,session_id,step_id,is_terminal"
# Count rows matching a SQL filter
python scripts/inspect/query_data.py --table wt_landing \
--query "job_id LIKE '%panjia%' AND is_trainable = true" --count
# Decode and inspect JSON payload columns without display truncation
python scripts/inspect/query_data.py --table landing_test --limit 1 \
--show-nested --no-truncate
# Dump one sample row to a local JSON file, expanding JSON payload columns
python scripts/inspect/query_data.py --table landing_test \
--query "job_id = 'job-001'" --limit 1 \
--output ./artifacts/landing_job_001_sample.json
# Dump selected production rows to a local JSON file
python scripts/inspect/query_data.py --table wt_landing \
--query "job_id LIKE '%panjia%' AND is_trainable = true" \
--columns "id,job_id,session_id,step_id,source_updated_at" \
--output ./artifacts/panjia_trainable_rows.json
# Show expected versus existing scalar indexes by partition
python scripts/inspect/show_table_indexes.py landing_test
# Show aggregate fragment statistics and index coverage for selected HASH buckets
python scripts/inspect/show_partition_status.py --table landing_test \
--partition 34 --partition 94
# Inspect every logical bucket, including buckets that have not materialized yet
python scripts/inspect/show_partition_status.py \
--table wt_landing --all-partitions
# Column definitions and STATE meanings are documented in scripts/README.md.
# Scan a logical table for duplicate IDs
python scripts/inspect/scan_duplicate_id.py --table landing_test --max-output 100
# Legacy diagnostic for payload decode failures in pre-JSON-schema data
python scripts/inspect/scan_landing_nested_decode.py --table landing_test
# Inspect serving tags and ETL-generated search text
python scripts/inspect/get_unique_tags.py --table wt_serving
python scripts/inspect/check_search_text.py --table wt_servingFiltered cleanup on the four active landing/serving tables uses SDK HASH
bucket pruning for exact job_id = '...' predicates and only reads lightweight
preview/count columns during dry-runs.
# Preview matching landing data before deletion
python scripts/ops/cleanup_data.py --table landing_test \
--query "job_id = 'job-001'" --dry-run
# Delete matching test data
python scripts/ops/cleanup_data.py --table landing_test \
--query "job_id = 'job-001'"
# Preview dirty test env config rows; this table automatically uses WT_SDK_ENV_CONFIG_DB_URI
python scripts/ops/cleanup_data.py --table env_test \
--query "job_id = 'gateway'" --dry-run
# Delete dirty test env config rows after preview
python scripts/ops/cleanup_data.py --table env_test \
--query "job_id = 'gateway'"
# Preview and patch filtered landing rows in the test profile
python scripts/ops/update_table_rows.py --profile test --table landing \
--query "job_id = 'job-001' AND session_id = 'session-001'" \
--updates '{"is_session_completed": true}' --dry-run
# Patch filtered serving rows in production (exact-table confirmation required)
python scripts/ops/update_table_rows.py --profile prod --table serving \
--query "job_id = 'job-001' AND id = 'record-001'" \
--updates '{"is_session_completed": true}'
# Create missing indexes and optimize every existing landing bucket
python scripts/ops/maintain_table_indexes.py \
--table wt_landing --all-partitions
# Create missing indexes and optimize every existing serving bucket
python scripts/ops/maintain_table_indexes.py \
--table wt_serving --all-partitionsupdate_table_rows.py only targets the active landing/serving table selected
by --profile; it does not accept custom or legacy table names. It skips rows
already at the requested values, refreshes the role-specific SDK timestamp,
and reports the row count confirmed by a latest-snapshot read after the update.
scripts/dev contains disposable test-table setup helpers. scripts/migrations contains completed historical migrations and is not routine setup. See scripts/README.md for the full layout.
wt_sdk/ Public SDK package
wt_sdk/etl/ Optional ETL runtime, CLI, tools, docs, and tests
scripts/ops/ Operational commands
scripts/inspect/ Read-only diagnostics
scripts/dev/ Disposable test-table setup
scripts/migrations/ Historical one-time migrations
tests/unit/ Default hermetic test suite
tests/integration/ Explicit real DLDB/S3 tests
MIT