Skip to main content

kestrel-cloud-runpod

Runpod GPU cloud provider for Kestrel Sovereign agents. Provision Pods, run LoRA training, manage Pod lifecycle, and submit queue-based Serverless jobs without using Runpod's v1 or GraphQL infrastructure APIs.

See CHANGELOG.md for release notes.

Installation

Requires Core >=0.63.0 (excluding 0.64.0) and SDK >=0.49. Core and this package retire fresh legacy training/generation admission together; original historical recovery remains. Core 0.64.0 has a confirmed cold tool-effect import regression tracked in Core #4003.

uv pip install kestrel-cloud-runpod

The feature is auto-discovered by Kestrel Sovereign via the kestrel_sovereign.features entry point. Private inference is independently registered as runpod in kestrel_sovereign.inference_lease_providers; Kestrel core interacts only with the public SDK lease contract and never imports this package.

CPU Pod requests

The low-level v2 client accepts PodCreateRequest for GPU Pods and CpuPodCreateRequest for CPU Pods, both from kestrel_cloud_runpod.models. Construct requests with keyword arguments. CPU requests specify cpu_id and vcpu_count; Runpod assigns RAM from the selected flavor. Both variants share the same container settings and RunpodControlPlaneClient.create_pod path. CPU requests reject GPU/CUDA options, persistent container mounts and global networking. Only a single explicit network-volume mount is supported; global-volume mounts are intentionally unsupported by this request type.

These request types are provider primitives. Accepted quotes, durable environment custody, browser transport and visual conformance remain tracked in #43. The existing GPU tools, inference profiles and capacity service remain GPU-only. PodResource.cost_per_hr is None when the provider omits its rate; a reported zero remains zero. A malformed successful create response requires reconciliation and never authorizes automatic replay. Unexpected success statuses also retain creation custody. Malformed inventory entries refuse the complete read, so reconciliation remains pending rather than silently treating a resource as absent.

CPU catalog discovery

RunpodControlPlaneClient.list_cpus(product=ComputeProduct.POD, vcpu_count=4) reads the v2 CPU catalog with availability scoped to that exact product/count. The immutable snapshot retains its observation time, flavor bounds, RAM ratios, separate Pod/Serverless rates and per-datacenter stock. Unknown stock or price stays unknown; example prices are never defaults.

snapshot.match_pod(request, now=..., max_age=...) checks a CPU request against those facts. It requires explicit datacenters, a matching secure Pod query, a supported flavor/count, fresh observations and sufficient stock in every requested datacenter. It refuses a mismatch instead of selecting another region, product or flavor. The returned compute rate is per Pod, multiplied by vCPUs; it excludes disk, storage, transfer and other charges. RAM is derived from the flavor ratio. Calculations are independent of ambient decimal precision.

A catalog match is neither a reservation nor an accepted spend quote. Placement may change after observation, and network-volume attachment compatibility needs separate validation. The environment provider must still acquire fresh all-in pricing, authorization and durable cleanup custody before provisioning. No CPU provisioning tool is registered by this package yet.

cpu_environment.CpuEnvironmentPlanner now builds an exact short-lived CPU acquisition intent from those production catalog facts, the original SDK EnvironmentRequest, a digest-pinned requested profile and explicitly bound finite disk/transfer/cleanup cost estimates. It checks both original cost ceilings and revalidates the same inputs before emitting a typed CPU Pod request. It does not provision, own a separate lease store or advertise a secure visual provider. The API's data-center field is a placement preference: actual region, CPU shape and billed Pod rate must be verified before readiness, with original-custody teardown on a mismatch. Published Core 0.55.0 does not supply that new visual runtime. See CPU environment prerequisites for the remaining browser transport, original-custody and teardown gates.

Configuration

Variable Description
RUNPOD_API_KEY RunPod API key (required)
RUNPOD_CLOUD_TYPE Default Pod cloud: SECURE or COMMUNITY; overrides manager.cloud_type
RUNPOD_SERVERLESS_API_KEY Restricted Serverless invocation key for Ollama endpoint probes and model pulls
RUNPOD_OLLAMA_BEARER_TOKEN Workload-scoped token enforced by the reviewed Ollama Pod image
RUNPOD_CONTROL_PLANE_BASE_URL Optional dev override; must end in /v2
RUNPOD_USER_AGENT Optional non-empty application User-Agent override
RUNPOD_OLLAMA_IMAGE Immutable ghcr.io/kestrelsovereignai/kestrel-cloud-runpod-ollama-runtime@sha256:... reference
RUNPOD_OLLAMA_ALLOWED_MODELS Comma-separated operator allowlist of name:tag@sha256:<digest> model pins
RUNPOD_OLLAMA_LEASE_DB Optional absolute override for the durable SQLite lease store
RUNPOD_OLLAMA_SERVERLESS_NON_COMPUTE_ESTIMATED_USD Operator-estimated per-session Serverless non-compute authorization
RUNPOD_OLLAMA_SERVERLESS_NON_COMPUTE_MAXIMUM_USD Conservative per-session Serverless non-compute authorization ceiling
RUNPOD_OLLAMA_POD_NON_COMPUTE_ESTIMATED_USD Operator-estimated per-session Pod non-compute authorization
RUNPOD_OLLAMA_POD_NON_COMPUTE_MAXIMUM_USD Conservative per-session Pod non-compute authorization ceiling
RUNPOD_POD_CAPACITY_LEASE_DB Absolute canonical SQLite store for catalog and migrated training Pod leases
RUNPOD_TRAINING_LEASE_DB Optional absolute override for durable training Pod ownership state

Runtime settings and profiles live in the standalone $KESTREL_HOME/runpod_config.toml; runpod_config.toml.example is the canonical shape. RunPodManager(config=...) may receive that same mapping explicitly. This package does not read a [runpod] section from kestrel.toml.

Pod cloud configuration is resolved once when constructing the manager: RUNPOD_CLOUD_TYPE overrides manager.cloud_type, which defaults to SECURE. An explicit profiles.<name>.cloud overrides that default for that profile; Pod metadata can explicitly override the selected profile cloud. Catalog selection and create requests use the same selected cloud. Invalid or empty cloud settings fail rather than falling back. Configuration accepts case and surrounding whitespace; persisted resource authority remains strictly decoded.

Applications quoting a single Pod cloud must call manager.require_uniform_profile_cloud() and inject the returned CloudType into pricing. Pass expected=... to reject a disagreement with an independently configured pricing cloud. Mixed profile clouds are supported by the manager, but cannot be represented by a single-cloud price quote. Historical resource cleanup uses the saved resource identity, not the current default cloud.

What's provided

  • RunPodFeature — agent-facing tools for pod search, provisioning, training, lifecycle
  • Standalone API: RunPodManager for direct programmatic use
  • RunpodControlPlaneClient — typed v2 catalog, Pod, Serverless endpoint, worker/log, and billing client
  • RunpodServerlessClient — typed queue job run/status/cancel/retry/health client
  • RunpodServerlessCapacityProvider — read-only finite-job capacity quotes, pre-submit drift validation, and authoritative content-free billing receipts
  • Durable RunPod-backed private Ollama leases with readiness and cost gates
  • Provider-neutral SDK 0.34 inference leases with OpenAI-compatible host-only routes
  • Durable LoRA training Pod ownership, cleanup tokens, and restart reconciliation
  • Generic single-attempt Pod capacity with live quotes, scoped bearer transport, deterministic recovery, immutable content-free realized/worker evidence, permanent termination, and authoritative Pod billing
  • Read-only PodCapacityQuoteService composition for ephemeral/scaled API processes that must never construct the writable SQLite lease authority

Catalog hosts with revocable owner/generation admission should use PodCapacityLeaseService.provision_catalog(request) for the bounded provider create and durable locator transition, then poll_catalog_readiness(...) on their existing external worker loop. Each poll performs one readiness observation (it may terminate unusable/expired capacity), never sleeps, creates, or restarts a Pod. acquire_catalog() retains its wait-until-ready behavior for existing callers. Polling is not permission to submit: revalidate owner, generation and durable Stop immediately before workload submission, including recovery. An old resource may still be observed, terminated and settled after its authority to create or submit work is revoked.

await_owned_effect(effect) retains an already-admitted mutation through repeated task cancellation. Persist intent before admission, include provider receipt or ambiguity persistence inside the effect, and hold the host's admission/Stop custody outside the await. Caller cancellation propagates after the entire effect finishes; a late effect error remains visible. This is not a retry or an authorization mechanism. Process crashes still require recovery from durable intent. Provider adapters use this same primitive to join blocking Pod and Serverless mutation threads before returning control.

Architecture

Runpod has two distinct v2 services:

Service Default base Authentication Use
Control plane https://api.runpod.io/v2 Bearer API key Catalog, Pods, endpoint definitions, workers/logs, billing
Serverless data plane https://api.runpod.ai/v2 Bearer API key Queue job run, status, cancel, retry, and health

Both clients set an explicit application User-Agent. Base URLs are injectable for testing but must end in /v2; there is no v1 or GraphQL production fallback. Pod, endpoint, and network-volume inventories follow every cursor page and reject incomplete or cyclic pagination. Pod inventory includes cluster members so cleanup checks cannot mistake an incomplete inventory for an empty account.

Placement uses the product's catalog rate: price.secure/community for Pods and price.serverless for Serverless. A missing Serverless pool price is ineligible for a paid quote; a Pod rate never substitutes for it.

Accepted CUDA floors are sent in resource create requests, not only used to filter catalog observations. Finite Serverless capacity readback verifies that floor before dispatch. Both finite capacity and private Ollama check all network/global mount fields before workload requests. Global mounts are unsupported by these workload profiles and fail clearly. Re-quote before creating new resources after upgrading; existing resource cleanup retains its exact IDs.

Resource schema version 2 is written by new Serverless endpoint specs. Unversioned, historical specs are decoded as version 1 with their original digests, for adoption and cleanup only. Upgrade the external worker before enabling new API writers; cancel/re-quote pending historical operations instead of authorizing new work from a version 1 plan.

The control-plane client's max_inventory_pages defaults to 1,000 pages. Exceeding that configurable bound fails the entire inventory, so a provider issuing endlessly unique cursors cannot hang reconciliation indefinitely.

Direct client example

from kestrel_cloud_runpod import RunpodControlPlaneClient, RunpodServerlessClient
from kestrel_cloud_runpod.models import ComputeProduct

control = RunpodControlPlaneClient(api_key="...")
offers = control.list_gpus(products=(ComputeProduct.SERVERLESS,))

jobs = RunpodServerlessClient(api_key="...")
job = jobs.run("endpoint-id", {"prompt": "hello"})
status = jobs.status("endpoint-id", job.id)

Read-only cold-start observations

control.endpoint_cold_start_metrics(endpoint_id, start_time=..., end_time=..., interval="1h", limit=1000, max_pages=1000) reads the v2 cold-start series through the existing authenticated control-plane transport. All query parameters except the endpoint identity are optional. Timestamps must be RFC3339 strings; page size is an integer from 1 to 1000. Runpod owns its retention clock (90 days), default window and future-end clamp; provider validation failures remain errors.

The immutable observation retains the endpoint identity, read-start time, typed pages, resolved window/interval, original pagination boundaries and vendor duration statistics. observation.records is the ordered concatenation of only the returned buckets: missing or empty activity does not become zero-filled data. Duration totals retain the parsed JSON numeric value as a Decimal, not the original wire lexeme. Percentiles remain per bucket; do not average them. Window comparisons preserve arbitrary RFC3339 fractional precision and accept equivalent offset spellings. start_time and end_time are microsecond-limited datetime views; start_time_text and end_time_text retain the full original timestamps on both observations and pages. Validation uses exact instants, not rounded datetime views or raw-string equality. Datetime views retain the received offset. Exact integer UTC coordinates avoid overflow at offset boundaries while forwarding future end times unchanged for Runpod to clamp; no local clock substitute or timestamp fallback is used.

Every page uses the same original query and exact opaque cursor. The entire read fails on malformed responses, cursor cycles, the configurable page bound, changed resolved windows, non-UTC-aligned/overlapping/unordered buckets or exceeded page size; no partial success is returned. This shares inventory's cursor walker and does not change existing inventory bounds or resource-identity checks.

Cold-start duration is neither queue delay nor end-to-end application startup. This method does not create workers, submit jobs, download models, change lease authority, or establish readiness, actual billing or teardown. Actual Kite dogfood must separately measure image pull, model download/load, readiness and first output, plus actual cost and cleanup, under an approved live budget.

Finite Serverless capacity and billing

ServerlessCapacityQuoteRequest binds a normalized inference-parameters SHA-256 and workload kind to one configured immutable queue-endpoint profile. A quote performs only GET /catalog/gpus?product=SERVERLESS&include=AVAILABILITY and GET /serverless/{id}. It records schema/contract versions, the profile digest, exact GPU/pool/data center, catalog observation, live worker rate, benchmark, queue/startup/execution/idle timing bounds, maximum billable seconds, estimated cost, maximum cost, expiry, and the exact per-job execution-timeout and queue TTL policy. Execution timeout is constrained to 5 seconds through 7 days and job TTL to 10 seconds through 7 days; the quote freshness TTL remains at most five minutes. The authorized job TTL must cover the full maximum queue, worker-start, and execution interval. The caller supplies explicit estimated and maximum non-worker amounts so disk and platform fees are included in the wallet reservation rather than hidden behind the GPU rate. Generated content, endpoint request URLs, worker configuration, credentials, and raw provider bodies are never serialized. Finite-job profiles reject persistent network volumes because their continuing cost cannot be attributed to one attempt.

Call validate_quote_for_submission() immediately before /run. It repeats the two read-only observations and rejects expiry or endpoint, GPU, pool, data-center, profile, or upward-rate drift. It does not submit a job, reserve funds, or own catalog state; those operations remain the host application's responsibility. A quote-only process needs no Serverless job client. Billing reconciliation adds a separately restricted status client but still performs GET requests only.

Runpod v2 currently reports Serverless billing in endpoint-level hourly buckets, not per-job records. final_billing() therefore returns an authoritative receipt only after the exact job is terminal, its complete closed billing window is available, the endpoint is configured as scale-to-zero with one worker, and the caller supplies the digest and complete UTC hour allocation of a durable host-owned exclusivity record proving that no other attempt shared any reserved endpoint-hour bucket. That canonical allocation may be a conservative superset reserved from before submission through quote expiry plus the worst-case job duration; it must fully cover the exact submission-through-completion-plus-idle interval. Settlement queries every reserved hour and waits for the final one to close. A missing, partial, or still-open bucket remains pending. Any identity, interval, total, component, or unsupported-field mismatch fails closed. The receipt binds the accepted quote, profile, endpoint, job, attempt, accepted idle-tail duration, exact billable coverage end, and every exclusive hour while projecting Runpod's aggregate queue-plus-cold-start delayTime as pre_execution_delay_ms. The unavailable worker-startup split and observed idle-tail value remain null.

If /run returns an ambiguous transport or server error before a job ID is known, the host keeps the same exclusive worst-case endpoint/hour allocation and calls final_ambiguous_window_billing(). This Cloud method needs no job status client. The exact attempted-at worst-case interval must be fully covered by the canonical allocation, including any earlier or later quote-lifetime hours. After every allocated hour closes, it reads only strict v2 endpoint-hour billing and returns content-free actual, accepted-ceiling-capped, and operator-loss amounts. The receipt's canonical ordered endpoint-hour costs retain each v2 record's UTC start/end, endpoint ID, component amounts, total, and a stable provider-observation ID derived from that complete normalized record; aggregate amounts must equal their sum. Empty or incomplete billing remains pending because v2 exposes no finalization marker; consumers never call the control-plane billing client directly or substitute an estimate for actual spend.

After an activated endpoint is physically retired, retired_endpoint_billing(original_request, original_quote, activation, cleanup) reads only the global GET /billing/serverless history. It needs no job, submission, or data-plane status read. The exact original activation and verified idle/delete/absence receipt bind the full lifecycle from create admission through verified absence, including startup, idle, and cleanup costs outside a finite job's authorization window. Expired historical quotes remain valid for this read-only recovery; they cannot authorize new spend. Queries use contiguous hour batches, configurable with billing_history_batch_hours (default 24), and reuse the same strict record, query, count, and component-total validation as ordinary job billing. An open last hour or any empty/incomplete batch remains pending, never an assumed zero.

ServerlessRetiredEndpointBillingReceipt is an endpoint-lifecycle observation, not a per-job charge or provider invoice-finality proof: provider_finality_confirmed is always false. The API does not document a finalization marker or a guarantee of deleted-endpoint billing retention; if history becomes unavailable, reconciliation fails closed. The host must retain unresolved settlement/cleanup custody and apply its explicit final-settlement policy before erasing it. It must also reconcile overlapping job/window costs by endpoint and UTC hour, not add both receipt totals. A later provider cost revision changes that hour's observation ID and the lifecycle receipt ID; it is a revision of the same hour, not a second charge. Cost totals are derived without rounding from the canonical hourly records. No estimate, quote cap, automatic operator loss, or fabricated job is substituted for observed spend.

Create calls are never retried automatically. If a connection failure or 5xx makes a Pod, endpoint, or queue-job creation result ambiguous, the client raises RunPodAmbiguousResultError with reconcile_required = True. Ollama leases persist the request fingerprint and deterministic resource name before creation, then recover by listing before any replacement could be authorized.

Private Ollama callers submit a stable OllamaLeaseRequest with owner/workload IDs, the exact model, placement constraints, expected warm utilization, an idle timeout, hard deadline, and maximum spend. The service compares current Pod and Serverless catalog offers. Bursty traffic can use native load-balanced Serverless; sustained sessions can use a dedicated Pod. Queue Serverless is not selected for interactive streaming. lease.public_route_url remains None until both Runpod health and Ollama /api/tags prove the requested model is ready. An external scheduler must run RunPodManager.reconcile_ollama_leases() periodically so expiry and teardown retries survive requester crashes. The kestrel-runpod-reconcile-ollama command performs one fail-fast pass and is suitable for a timer or job runner.

Kestrel normally reaches that lifecycle through RunpodInferenceLeaseProvider. quote() reads the v2 catalog but creates nothing; acquire() returns PENDING after the one durable billable mutation; and status() reconciles readiness until the exact allowlisted model is loaded behind an authenticated /v1 route. SDK 0.35 touch() re-observes that exact route before durably renewing its idle deadline, preserves the owner and lease identity, and fails closed without provisioning replacement capacity when the route is no longer ready. Quote selection uses one immutable all-in plan: live GPU compute estimate/ceiling plus the deployment-supplied estimated/maximum non-compute authorization. The catalog prices each GPU individually, so a placement that attaches several is rated at that multiple of the offered rate; Serverless worker scaling is a separate factor applied to billable seconds, so GPUs-per-worker and maximum workers never substitute for one another. Affordability uses the all-in ceiling, while the SDK quote's standard total is the all-in estimate. Its content-free metadata exposes the compute/non-compute breakdown and explicitly labels it conservative authorization rather than observed provider billing. Requests that cannot meet their region, readiness, privacy, concurrency, or total-cost limit fail before provisioning.

Set quote_ttl_seconds, serverless_estimated_ready_seconds, and pod_estimated_ready_seconds in [ollama_leases] from measured p95 startup data. Configure at least one exact profiles.ollama.allowed_data_center_ids; the provider advertises those normalized IDs as its regions and constrains the v2 create request to the quoted region. A shared model network volume reduces download time, but can narrow placement availability and Serverless requires a single writer.

Both [ollama_leases.serverless_non_compute_cost] and [ollama_leases.pod_non_compute_cost] are mandatory and deliberately contain no built-in Runpod rates. Operators must supply per-session estimated and maximum amounts from their current deployment/billing policy. Each policy must attest the applicable covered_components: container disk, model transfer/egress, retry allowance, and network_volume when the profile mounts one. Missing, stale, non-finite, incomplete, or estimate-above-maximum policy fails closed before catalog selection. Update these values when storage size, region, model size, transfer behavior, retry allowance, or Runpod pricing changes.

The GA catalog observed on 2026-10-17 maps PRO 6000 MIG 1g.24gb to AMPERE_24 and 2g.48gb to ADA_48_PRO. Both pools also contain other GPU types; these IDs do not guarantee MIG or Blackwell placement. All Serverless placement (including private Ollama) requires an unambiguous GPU-to-pool mapping and rejects shared pools before creation. Missing pool IDs are rejected too; Kestrel never guesses one from a marketing name or GPU ID. See #21. A separately valid Pod offer may still be quoted explicitly as Pod capacity.

Upgrade the controller before accepting new work. Historical Serverless authorities remain usable only for recovery, billing and cleanup, not new quotes or submissions. Drain and clean up those resources before replacing their authority; do not PATCH their CUDA or mounts in place. A reusable endpoint must already match the accepted CUDA and storage policy. If it does not, drain it and create a correctly constrained replacement instead of reusing an incompatible endpoint.

The route endpoint and bearer are reconstructed from a fresh authenticated provider observation and live only in the SDK InferenceRoute. They are never written to provider lease rows or public metadata. On process restart, status() re-observes the same deterministic Runpod resource and returns a fresh host-only route without creating duplicate capacity.

manage_gpu remains available for explicit operator stop/status/log controls over already retained sessions, but ownerless legacy start and stopped-Pod resume are retired before any billable provider action. New private inference uses the provider-neutral inference-lease coordinator; catalog and training capacity use their durable Pod-capacity services. The legacy tool never attaches, detaches, or reports an LLM route.

Legacy stop_session and terminate_session share the original durable capacity-release boundary. A cached ownerless Pod ID is not mutation authority: the call refuses without a provider action or fabricated wall-clock charge and retains its handle for operator reconciliation. Use the existing owned lease's release/reconciler API, not a new ledger or a replacement acquisition. terminate_session returns that original release result when one exists; callers that only await it may continue to ignore the result. Borrowed capacity can be released locally without stopping its provider resource. Confirmed capacity cleanup does not imply provider invoice finality or zero storage cost. If cancellation or reconciliation already completed the same original release, stopping its retained session is idempotent: it reuses that result without another provider action. Exact session/lease identity remains mandatory; completed leases still cannot authorize workload operations. The old set_metering_callback registration now refuses explicitly: elapsed session time is not a provider bill. Consume the canonical lease/capacity billing observations rather than registering a callback that cannot run.

Control-plane, Serverless data-plane, and Pod workload credentials are separate. The reviewed private Ollama runtime is published independently to GHCR. RUNPOD_OLLAMA_IMAGE must select it by immutable digest; mutable tags and other repositories fail before a billable create call. The runtime enforces bearer authentication on every non-health route, expires the workload capability at the lease deadline, permits only digest-pinned operator models, and never receives Kestrel's control-plane credential. Every operator-allowlisted model must support Ollama completion and tools; readiness revalidates both so Kestrel's default full-agent route never falls back to a tool-free lane. The provider refuses to publish a Pod route unless an anonymous /api/tags probe receives 401 or 403. Tokens are never returned in lease state. AUTO mode considers only products whose scoped credential is configured.

For load-balanced Serverless, use a Runpod key restricted to the one endpoint as the scoped inference capability. Runpod authenticates it at the edge and the workload proxy verifies the same bearer defensively. For a dedicated Pod, RUNPOD_OLLAMA_BEARER_TOKEN is the scoped capability. The provider rejects either workload credential when it matches RUNPOD_API_KEY, and rejects one credential reused across both products. Rotate the Pod value per bounded lease/deployment; never reuse the full control-plane key. Both modes expose /ping on port 11434, returning 204 during model preparation and 200 only while Ollama is live, the capability is unexpired, and the exact pinned model remains present.

accrued_estimated_cost is the conservative accrued-compute bound, not settled billing. Every lifecycle gate adds the durably reserved maximum non-compute authorization before comparing with the SDK request cap. The plan also proves that maximum compute through the hard deadline plus reserved overhead is within that cap, so a missed polling interval cannot authorize excess spend. Dedicated Pods accrue their continuous live catalog rate. Serverless uses wall-clock rate times the configured maximum workers until authoritative worker billing exists. Its expected-compute quote also covers every possible scale-to-zero cycle in the expected session: active time plus one initialization and idle tail for the initial worker and for every complete idle interval. A zero idle tail cannot produce a finite invocation-independent quote, so it is not eligible for interactive Serverless. Actual provider settlement remains a separate billing concern and must never be inferred from these authorization ceilings.

PodCapacityLeaseService is the one writable dedicated-Pod lifecycle for new catalog attempts and old training callers. It quotes an exact live v2 GPU ID, display name, hourly price, startup/execution estimate, maximum runtime, and cost ceiling. Acquisition requires that exact quote, parameter digest, request digest, owner/workload/attempt identity, immutable worker image digest, and accepted cost ceiling. A unique bearer is loaded from an injected encrypted capability store and injected only into the one Pod; SQLite keeps its secret ID, digest, and expiry, never the token or private catalog payload.

The public lease projection omits even that internal capability metadata. New catalog rows expose a versioned evidence object with the accepted quote, validated realized GPU/cloud/data-center/rate, first-observed lifecycle times, an exact-bound allowlisted worker telemetry envelope, and authoritative billing. The private host records that projected envelope with record_catalog_worker_evidence() before acknowledging its durable result. Legacy rows expose evidence = None; no historical phase is inferred.

The workload transport carries the private catalog serializer's mapping unchanged to the schema-3 single-attempt runner. This public package does not import or publish frinz_catalog or frinz_catalog_contracts; those remain private GitHub-only dependencies in their owning repositories. Health is anonymous and content-free. Submit, status, result, and cancellation are attempt-bound and bearer-authenticated. Result retrieval is non-destructive and replayable after its attempt and request hashes match. The private host must strict-decode and durably accept the signed protocol-1 receipt/result envelope before calling acknowledge_catalog_result(capacity_id=..., owner_id=..., workload_id=..., acknowledgement=opaque_host_ack). This sends the runner's authenticated /acknowledgement request and persists exact content-free ACK intent and remote observation; it does not terminate the Pod. The host then durably confirms that exact acknowledgment in its private database and calls release_catalog_result(..., host_confirmed_acknowledgement_sha256=...). Only this separate host declaration drives successful-result teardown. If the runner process was replaced after private host acceptance but before actual remote ACK proof was persisted, call recover_catalog_result(..., recovery=opaque_private_recovery) instead of resubmitting execution. This uses only the authenticated /handoff-recovery route with the private host's existing envelope and exact ACK. The SDK derives and reserves CATALOG_POD_REQUEST_SHA256 from the sealed capacity request; user environment overrides are rejected. The worker image must implement that artifact-only recovery protocol before the host enables it. The SDK never imports the private schema, stores the result, mints a recovery credential, provisions replacement capacity, or submits execution as a fallback.

Fresh ACK and recovery both require the original live lease, unexpired Pod capability, and hard deadline, checked again immediately before transport. Cancellation-owned tails persist any genuine late proof without reviving Stop. Identical cached actual ACK proof replays before credential/deadline/terminal checks so historical host confirmation can finish after expiry or teardown; persisted ACK intent alone is never sufficient. This does not authorize new execution, publication, or spending. CPU transport/state tests are not live GPU or benchmark evidence.

Historical leases retain their explicitly legacy result/ack-cleanup behavior, but cannot authorize new acquisition or submission. RELEASED is not recorded until /billing/pods supplies final authoritative cost (or v2 definitively rejected creation, which records zero).

The 0.7 repository migration atomically renames training_pod_leases to pod_capacity_leases, backfills generic non-secret fields, and preserves every active, uncertain, ready, releasing, released, and fallback-family row. The old TrainingPodLeaseService, repository, and provider imports are aliases to the canonical implementation, so they cannot create a second lifecycle.

Legacy NEW start_training_pod(), submit_training_job(), start_inference_pod() and generate_with_lora() calls now refuse before new config/provider/model effects, even with a retained session/token. Use the authorized host catalog workflow for LoRA; a legacy FLUX path is not an accepted SDXL artifact or input. There is no replacement profile/provider fallback or second queue. Private LLMs use the durable inference-lease interface instead. Original native execution denial takes precedence over the ordinary retirement message.

Historical exact/root cleanup, status, cancellation and download remain on the SAME capacity ledger. Pre-existing running capacity is never stopped without lease authority; uncertain/retryable custody is retained. Run kestrel-runpod-reconcile-training for those original compatibility records. The compatible Core dependency floor must name the actual first published Core#3954 release before this candidate can release; the old floor is NOT cutover acceptance. See KCR#64. New catalog hosts construct PodCapacityLeaseService with their encrypted capability store and call reconcile() from a cheap external timer; process-local TTLs are never cleanup authority.

Legacy training error preservation: when an ordinary readiness, submission, recovery, or cancellation failure is followed by a control-bearing cleanup failure, the public call raises the canonical finite exception aggregate. It retains the same cleanup carrier and the same operation error (cleanup first), without rewriting the cleanup carrier's explicit cause or control evidence. Because both originals derive from Exception, the aggregate is an ExceptionGroup; callers must not assume it is the cleanup exception itself. Direct control failures and healthy-cleanup ordinary normalization keep their existing behavior. At error conversion, retry, persistence, or later-effect boundaries, use public Core is_execution_control_error(error) with its default recursive behavior and re-raise control-bearing evidence unchanged. Neither an error aggregate nor cleanup completion grants new work or financial finality.

Install one host-owned synchronous factory that constructs the public service with explicit Runpod v2 credentials, the absolute SQLite repository path, GPU profiles, the private encrypted CatalogAttemptCapabilityStore, and CatalogPodWorkloadTransport. Then schedule the installed one-shot command:

from kestrel_cloud_runpod import (
    CatalogPodWorkloadTransport,
    PodCapacityLeaseService,
    RunpodPodCapacityProvider,
    SQLitePodCapacityRepository,
)
from kestrel_cloud_runpod.providers import DirectRunPodProvider


def build_capacity_service() -> PodCapacityLeaseService:
    settings = load_host_settings()  # host-owned, fail-fast secret/config loader
    direct = DirectRunPodProvider(api_key=settings.runpod_api_key)
    return PodCapacityLeaseService(
        repository=SQLitePodCapacityRepository(settings.capacity_database_path),
        provider=RunpodPodCapacityProvider(direct),
        profiles=settings.gpu_profiles,
        poll_interval_seconds=settings.poll_interval_seconds,
        orphan_timeout_seconds=settings.orphan_timeout_seconds,
        capability_store=settings.encrypted_capability_store,
        workload_transport=CatalogPodWorkloadTransport(),
    )

The factory is construction-only: it must not quote, acquire, or contact a worker. Keep it in the private host package and point the command at its import path:

export RUNPOD_POD_CAPACITY_SERVICE_FACTORY='catalog_host.runpod:build_capacity_service'
export RUNPOD_POD_CAPACITY_RECONCILE_TIMEOUT_SECONDS='240'
kestrel-runpod-reconcile-capacity

For example, a systemd timer can invoke that command once per minute with the two non-secret settings above and RUNPOD_API_KEY supplied by its credential store. The command never acquires capacity. It takes a nonblocking advisory lock derived from the canonical database path, runs one bounded reconcile() pass, and emits one content-free JSON object. Exit 0 means the pass completed; 75 means another invocation owns the lock, the pass timed out, or durable state requires retry; 78 means host configuration/auth construction failed; and 70 means a typed runtime failure. Error output never includes exception messages, identifiers, routes, payloads, tokens, or provider response bodies.

A host crash before its result transaction commits can repeat retrieve_catalog_result() against the same worker. Acknowledgement is the destructive boundary and must follow the private durable commit; the hard runtime deadline remains the final cost and cleanup bound.

After acknowledgement, poll get_catalog_capacity(capacity_id=..., owner_id=..., workload_id=...). It fails closed on either binding mismatch and returns the canonical lease only; settlement is usable only when settlement_ready is true, at which point billing_receipt is authoritative. A succeeded launch gate additionally requires terminal_success_evidence_complete. The host never reads the capacity SQLite repository directly.

For cancellation/restart recovery that may run before acquisition, find_catalog_capacity(...) performs the same owner/workload authorization and returns None only when no capacity claim exists. It is non-mutating and never provisions a Pod; an existing lease with a mismatched binding still fails closed.

Configuration migration from 0.2

Profiles no longer select a hardcoded gpu_type_id or record a cost_per_hr. Replace legacy fields with workload constraints:

[profiles.image]
name = "Large-memory image generation"
task_type = "image"
image_name = "runpod/kestrel-flux:latest"
min_vram_gb = 40
min_cuda_version = "12.8"
max_cost_per_hr = 3.00
gpu_count = 1

At Pod creation time, the direct provider queries v2 with product-specific availability, rejects offers outside the profile constraints, and records the selected GPU and offered live rate on the session. Legacy gpu_type_id, vram_gb, cost_per_hr, and template_id fields fail with migration guidance. Use registry_id for a v2 registry credential.

The old private CLI SSH helper is also gone. RunPodManager.get_logs() uses the v2 SSE Pod log endpoint. Arbitrary commands must be exposed as scoped workload HTTP operations.

OpenAPI pin

The reviewed v2 schema is pinned in vendor/runpod-v2-openapi.yaml with its checksum in vendor/runpod-v2-openapi.lock.json. Unit/contract CI validates the operations and shapes Kestrel consumes. A weekly/manual workflow compares the live schema and reports semantic drift without overwriting the pin.

Dependencies

  • kestrel-sovereign-sdk>=0.49.0,<1 — features, tools, and inference-lease contracts
  • kestrel-sovereign>=0.63.0,!=0.64.0,<1 — coordinated retirement of fresh legacy Runpod training/generation admission, providing canonical joined-effect custody, provider-neutral inference terminal-evidence refresh, and direct-node execution-control classification
  • httpcore>=1.0.9,<1.1 and httpx>=0.28.1,<0.29 — reviewed public transport exception pairs for bounded safe-read retry classification; implicit backend context is diagnostic only and mutating requests are never automatically retried
  • requests>=2.32,<3

Development

uv pip install -e '.[test]'
uv run pytest
python scripts/check_runpod_openapi.py --check-pin

An authenticated smoke test is opt-in, read-only, and lists the GPU catalog only:

RUNPOD_API_KEY=... uv run pytest --run-cloud tests/test_runpod_smoke.py

Public package releases

Publication accepts only a vX.Y.Z release tag, including manual dispatch (refs/tags/vX.Y.Z is also accepted). The workflow validates the tag against package metadata, resolves it once to a commit, and passes that same immutable SHA to every reusable CI checkout and the artifact build. Moving a tag after resolution cannot change the tested/built revision. Ordinary non-release CI keeps its event checkout, including the synthetic PR merge.

The existing protected pypi environment and trusted publisher are unchanged. This public package's workflow never publishes private Frinz/catalog/contracts.

License

Apache-2.0

Metadata

Release files for kestrel-cloud-runpod 0.17.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kestrel-cloud-runpod 0.17.0
File Size Uploaded Provenance Actions
kestrel_cloud_runpod-0.17.0.tar.gz 288.7 kB With provenance Details for kestrel_cloud_runpod-0.17.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kestrel-cloud-runpod 0.17.0
File Interpreter ABI Platform Actions
kestrel_cloud_runpod-0.17.0-py3-none-any.whl Python 3 none any Details for kestrel_cloud_runpod-0.17.0-py3-none-any.whl

Total release size: 589.2 kB

Release files / kestrel_cloud_runpod-0.17.0.tar.gz

Download URL kestrel_cloud_runpod-0.17.0.tar.gz
Size 288.7 kB
Tags Source
SHA-256 checksum
How to use checksums
1b1ddd5a383c2679d723e863a2d176e5b6057aa6fae76cd67745bc825069cba0
BLAKE2b-256 checksum
How to use checksums
966ade928cb74cd97be8277283ee77f074c6d1db01a7dbe5fa8aff9718a9b241
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

Release files / kestrel_cloud_runpod-0.17.0-py3-none-any.whl

Download URL kestrel_cloud_runpod-0.17.0-py3-none-any.whl
Size 300.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8b2786e7b86dc3fc3ec9d7e82e3b89fa66f82bb8dbc6fc29869dc96bd479feaf
BLAKE2b-256 checksum
How to use checksums
8fcb7d40095501a42ffdde3874d220a28848c4b81b6592e2fb3287170d76df1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

Security for kestrel-cloud-runpod 0.17.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kestrel_cloud_runpod-0.17.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page