Python API and environment reference
Look up the public runpod-doc-worker functions, environment variables, defaults, and transport limits.
This reference covers the public functions intended for worker composition in v0.1.0. The package is pre-release, so pin a tag and review changes before upgrading.
Root package
from runpod_doc_worker import WorkerConfig, active, configure, __version__| Name | Purpose |
|---|---|
WorkerConfig | Immutable worker-owned configuration |
configure(config) | Install process-wide configuration |
active() | Return the active configuration |
__version__ | Installed package version |
DEFAULT_VOLUME_ROOTS is exported from runpod_doc_worker.config.
Input transport
From runpod_doc_worker.transport.io:
| Function | Result |
|---|---|
resolve_input_bytes(job_input) | Async (bytes, source_label) tuple |
resolve_volume_file(volume_path) | Contained, resolved Path |
max_inline_b64_chars() | Encoded length at which a file_b64 payload is refused |
volume_roots() | Effective allowed roots |
detect_format(file_bytes) | pdf, image, ooxml, or unknown |
telemetry_source_kind(source_label) | Bounded source category |
From runpod_doc_worker.transport.net:
| Function | Purpose |
|---|---|
require_http_url(url, *, field) | Parse and require an HTTP or HTTPS URL |
resolve_checked(url, *, field) | Resolve a host and reject disallowed addresses |
check_target(url, *, field) | Validate the target without fetching it |
The checked transport classes and private httpx/httpcore integration are implementation details.
Artifact contract
From runpod_doc_worker.contract.artifacts:
| Name | Purpose |
|---|---|
Artifact(key, patterns, kind, default, required) | Declare one response field |
ArtifactError | Raised when a required artifact is absent or unreadable |
validate(manifest) | Validate the manifest and return a tuple |
resolve(manifest, output_dir, basename, keys=None, report=None) | Read selected artifacts |
keys(manifest) | List declared keys in order |
Valid kinds are text, json, and b64map. required applies to text and json only.
From runpod_doc_worker.contract.degraded:
| Name | Purpose |
|---|---|
Report() | Collect what packaging had to drop or substitute across one or more entries |
Report.note(reason=..., file=..., artifact=None, error_type=None) | Record one loss and log it |
Report.entry() | The degraded value, or None when nothing was lost |
Report.count | Everything noted, including items the report does not list |
MESSAGE | The stdout warning every loss is logged under. Stable: alert rules and log mirrors match it |
ENTRY_KEY, MAX_ITEMS, VALID_REASONS | The response key, the item cap, the reason vocabulary |
Reasons are unreadable, unresolvable, outside_output_dir, and unsafe_name.
Result packaging
From runpod_doc_worker.transport.package:
| Function | Purpose |
|---|---|
package_results_entry(..., report=None) | Build one transport-specific result dictionary. Pass a job-wide Report; the returned degraded field remains entry-local |
package_inline(...) | Resolve selected manifest values |
package_tarball(output_dir, archive_format="tar.gz", report=None) | Return a base64 archive |
package_s3(output_dir, basename, archive_format="tar.gz", report=None) | Upload and presign an archive |
presign_ttl_seconds() | Read and clamp the S3 URL lifetime |
Valid transports are inline, tarball_b64, and s3. Valid documented archive formats are tar.gz and zip.
Scoping the local-fetch bypass
<PREFIX>_ALLOW_LOCAL_FETCH is set by an operator, but what it exempts is
every URL the worker fetches — and those URLs still come from callers. Turning it on
to reach a private document mirror therefore also lets a caller name
169.254.169.254 and be fetched. That is the deliberate trade of the variable, and
it is why the exemption should reach as few fields as possible.
Pass allow_local=False to check_target, resolve_checked or
resolve_checked_host for any URL you are not prepared to have the bypass cover.
None, the default, consults the operator's setting as before.
# `file_url` is caller-supplied too. Omitting the override means the operator's
# bypass, if set, covers it — which is what an endpoint serving its own private
# mirror wants, and an SSRF hole on an endpoint open to untrusted callers.
net.check_target(file_url, field="file_url")
# `server_url` names a service rather than a document, so nothing an operator
# switches on for their mirror should reach it.
net.check_target(server_url, field="server_url", allow_local=False)The distinction is not operator-owned versus caller-owned — every job field is caller-supplied. It is how much the operator meant to permit when they set the variable: fetching documents from their own network, not letting callers choose arbitrary internal services.
Response size
runpod_doc_worker.transport.response_size — refusing a response the gateway would
discard rather than have it dropped silently. Off unless a worker opts in; see
Packaging → the response-size cap.
| Name | Kind | Notes |
|---|---|---|
ENFORCE_RESPONSE_CAP | bool | False by default. Set True to refuse an undeliverable response |
MAX_RESPONSE_MB | int | 20, the /runsync ceiling. Raise to disable the refusal |
BULKY_ARTIFACT | str | None | The heaviest optional output, named in the refusal |
ResponseTooLargeError | exception | Raised by package_results_entry when enforcement is on |
ResponseBudget | class | One per response, so several entries are measured together |
exceeds_gateway_cap | function | The predicate, for a worker deciding before it packages |
measure_entry_bytes | function | Serialised size of an entry, escaping included |
oversized_response_error | function | The message, if a worker wants to report it itself |
refuse_if_undeliverable | function | Measure, check and raise in one call |
The client half has its counterpart, runpod_doc_client.describe_dropped_response,
for explaining a response that was dropped — against a worker without the guard,
or on /run where the cap is half as high.
Logging and redaction
From runpod_doc_worker.obs.logging:
job_id_varinfo(message, **fields)warning(message, **fields)error(message, **fields)debug(message, **fields)
From runpod_doc_worker.obs.redact:
compact(text, *, limit=2000)compact_url(url)
Metrics
From runpod_doc_worker.obs.metrics:
build(meter)instrument_names()register_counter(name, suffix, *, description, unit="1")register_histogram(name, suffix, *, description, unit="1")register_gauge(suffix, getter, *, description, unit="1")registered_gauges()
Requires the metrics extra: pip install "runpod-doc-worker[metrics]". The
package does not depend on OpenTelemetry otherwise, and build() raises a
RuntimeError naming this extra if the API is missing rather than losing gauge
observations silently on the first export tick.
build(meter) creates every instrument on a meter the consumer supplies and
returns the counters and histograms keyed by short name. Observable gauges are
not returned — they are pull-based and nothing addresses them by name. Every
exported name is <metric_namespace>.<suffix>; see
metric_namespace.
The base catalog is the set of measurements shared by every document worker:
jobs.total, pages.total, bytes_in.total, bytes_out.total, errors.total,
degraded.total, worker.cold_starts.total, worker.refresh.total,
job.duration, phase.duration, pages_per_second, input.size_bytes,
output.size_bytes, worker.warmup.duration, and the three
gpu.* gauges.
Anything a worker measures that others do not — a sidecar's startup duration, for instance — is registered by that worker. Registration is guarded on both namespaces, which are separate:
- Short names — the key a call site passes.
register_counterandregister_histogramrefuse a name the base catalog owns, and refuse to register one name as both kinds. Allowing either would build the shared series and then never write to it, while call sites addressing that name wrote elsewhere. - Exported suffixes — the published metric name. All three registration functions refuse a suffix already exported by a catalog instrument, a built-in GPU gauge, or another registration. Two instruments under one exported name is not an error downstream: the samples merge or become indistinguishable depending on the backend, and nothing reports it.
register_gauge takes a callable read on each export tick. Returning None skips
that tick, which is how a worker reports "not applicable" without a sentinel — a
readiness gauge on a worker with no sidecar should report nothing rather than 0,
since 0 means configured and broken.
Input coercion
From runpod_doc_worker.contract.coerce:
fail(message)fraction(name, value)positive_number(name, value)bounded_int(name, value, *, low, high)one_of(field, value, allowed, default)
Single-value validators. Each returns a normalised value or raises ValueError
prefixed input validation failed: , which is the prefix a client branches on to
tell a bad request from a broken worker.
fraction, positive_number and bounded_int refuse booleans explicitly, because
isinstance(True, int) is true in Python and a field set to true would otherwise
normalise to 1. The two numeric validators also refuse NaN, infinity, and integers
too large to convert to a float — JSON bounds none of those, and the conversion
raises OverflowError, which is not a ValueError and would escape the contract.
one_of behaves differently, in two ways worth knowing before you wrap it:
- It treats any falsey value as absent, so
False,0,""and[]select the default rather than being rejected. It therefore does not refuse booleans, and it is asymmetric about them:Trueis truthy, so it reaches the membership check and is refused, whileFalseis replaced by the default. A worker that must reject a boolean for an enum-shaped field checks the type before calling this. - A callable
defaultthat raises propagates unchanged. When the value is absent, the default's own failure is the failure and it names the operator's misconfigured variable; flattening it into a "not one of" message would hide which variable was malformed. A consumer catching onlyValueErrorwill not catch it.
Pass a callable default wherever resolving the default can itself fail, such as
reading an environment variable: an eagerly evaluated default rejects jobs that named
their choice explicitly and could not have been affected by it.
Diagnostics
From runpod_doc_worker.obs.debug:
collect_gpu_info()find_model_dir()probe_filesystem()
Diagnostic helpers return data for the consumer's handler. They do not create a RunPod probe route.
Hub validation
From runpod_doc_worker.testing.hub:
check(path)problems(hub)check_test_inputs(path, roots=None)
Environment variables
<PREFIX> is the env_prefix from WorkerConfig.
| Variable | Default | Used by |
|---|---|---|
<PREFIX>_VOLUME_ROOTS | Configured roots | Volume input containment |
<PREFIX>_ALLOW_LOCAL_FETCH | Disabled | URL target policy |
LOG_FORMAT | json | Log rendering; set text for local output |
LOG_LEVEL | info | Set debug to enable debug records |
BUCKET_ENDPOINT_URL | None | Required S3 endpoint |
BUCKET_NAME | None | Required S3 bucket |
BUCKET_ACCESS_KEY_ID | None | Required S3 access key |
BUCKET_SECRET_ACCESS_KEY | None | Required S3 secret |
BUCKET_REGION | None | Optional S3 region |
BUCKET_PREFIX | Empty | Optional object-key prefix |
BUCKET_PRESIGN_TTL_SECONDS | 3600 | S3 URL lifetime, clamped to 60 through 604800 |
HF_HUB_CACHE | Library default | Preferred Hugging Face Hub cache override |
HUGGINGFACE_HUB_CACHE | Library default | Legacy Hub cache override |
HF_HOME | Library default | Hugging Face home used to derive the Hub cache |
XDG_CACHE_HOME | Platform default | Cache root when Hugging Face overrides are absent |
Proxy environment variables are honored by URL fetching. A proxy is responsible for the destination policy of hostnames it resolves.
Input and diagnostic limits
| Limit | Value |
|---|---|
| Inline decoded input | 20 MiB |
| URL input | 200 MiB |
| URL inactivity timeout | 120 seconds |
| URL wall-clock budget | 300 seconds |
| Redacted text default limit | 2,000 characters |
| Hub description limit | 189 characters |
Task-oriented behavior and qualifications live in the input, artifact, packaging, and observability guides.