Work Run Correction SDK Examples
These examples are for developer scripts that need to submit and review Work
Run corrections, including retry-request decisions. Source-package correction
helpers are available in retvest-sdk; OpenAPI-generated correction SDK
methods and package-registry release evidence remain pending.
Current SDK Package Names
- TypeScript source package:
@retvest/client, exportingRetvestClient. - Python source package:
retvest_client, exportingRetvestClient.
The current SDK docs describe source-only packages, not package-registry
availability. retvest-sdk now exposes typed correction helpers for the pinned
Work Run surface; until retvest-platform publishes the reviewed OpenAPI
snapshot, treat exact operation IDs, scopes, and generated schema names as
platform-owned evidence.
Only automate the append-only correction states shown in the checked source fixture: pending, applied, rejected, and superseded. Do not infer hidden replacement, deletion, or rewrite behavior, and do not present these examples as generated-client or package-registry proof.
Verified source-package helpers:
| Runtime | Create and read helpers | Review helpers | Problem helpers |
|---|---|---|---|
| TypeScript | createWorkRunCorrection(), createCorrection(), listWorkRunCorrections(), listCorrections(), readCorrectionAudit() |
applyWorkRunCorrection(), applyCorrection(), rejectWorkRunCorrection(), rejectCorrection(), retryWorkRunCorrection(), requestCorrectionRetry() |
RetvestValidationError, workRunCorrectionProblemResult(), shouldRetryWorkRunCorrectionProblem() |
| Python | create_work_run_correction(), create_correction(), list_work_run_corrections(), list_corrections(), read_correction_audit() |
apply_work_run_correction(), apply_correction(), reject_work_run_correction(), reject_correction(), request_correction_retry(), retry_correction() |
RetvestValidationError, work_run_correction_problem_result(), should_retry_work_run_correction_problem() |
Shipped SDK-side limits match the pinned platform behavior: correction category
is capped at 80 characters; original assertion, corrected assertion, and
observed consequence are capped at 4000 characters each; corrected evidence key
is capped at 120 characters; evidence and rollback refs are capped at 240
characters each; resolution reason code is capped at 80 characters; resolution
note is capped at 2000 characters; list and audit reads accept limit values
from 1 through 100. Structured validation Problems expose
invalid_params: [{ name, reason }] on RetvestValidationError.problem.
The lower-level helper below remains as public docs source code for operators
who need to understand the request shape without depending on an SDK package.
It intentionally uses fetch and the public docs path convention instead of
claiming an OpenAPI-generated client surface. Confirm exact paths, operation IDs, auth scopes, request members, response members, and Problem extension fields
against the platform-owned OpenAPI snapshot before automating against a customer
deployment.
Do not run apply, reject, or request retry as unattended approval automation. A permitted reviewer should choose the action after inspecting the governed Work Run evidence. Keep example ids synthetic and never log bearer tokens, idempotency keys, raw correction text, customer documents, generated answers, citation bodies, private evidence refs, or full UUID-heavy payloads.
Environment
export RETVEST_API_BASE="https://retvest.example.internal"
export RETVEST_API_KEY="<scoped-api-key>"
export WORK_RUN_ID="wr_example"
export CORRECTION_ID="wrc_example_001"
export CORRECTION_EXPECTED_VERSION="1"
export WORK_RUN_EXPECTED_VERSION="7"
Review Action Retry Rules
Correction create is safe to replay only when the script sends the same request
body with the same Idempotency-Key. Treat the replay as confirmation of the
original pending row, not as a second correction.
Apply, reject, and request retry are reviewer decisions, so scripts must not auto-repeat them
unless the caller supplied an explicit Idempotency-Key and the expected version
the reviewer inspected. Retry request uses
expected_work_run_version from the Work Run state, not raw correction text. If
a review attempt times out without an explicit idempotency key, refresh the
correction ledger and ask the reviewer to choose again instead of inventing a
new key.
Retry code should parse Retry-After as either seconds or an HTTP date, and it
should use that delay only for safe reads or exact idempotent replays. A stale
expected version, invalid transition, tenant mismatch, or authorization Problem
is not a retry signal.
TypeScript Helper
import { RetvestClient } from "@retvest/client";
type CorrectionStatus = "pending" | "applied" | "rejected" | "superseded";
type CorrectionProblemCategory =
| "validation_failed"
| "version_conflict"
| "already_finalized"
| "forbidden"
| "tenant_mismatch"
| "rate_limited"
| "unavailable"
| "timeout"
| "idempotency_conflict"
| "invalid_transition"
| "unknown_problem";
type RetvestProblem = {
type?: string;
title?: string;
status?: number;
detail?: string;
category?: CorrectionProblemCategory;
code?: CorrectionProblemCategory;
instance?: string;
request_id?: string;
retry_after?: string;
};
type CorrectionRecord = {
correction_id: string;
work_run_id: string;
correction_sequence: number;
correction_status: CorrectionStatus;
receipt_type?: string;
rejection_reason_code?: string;
recorded_at?: string;
};
type CorrectionListResult = {
items: CorrectionRecord[];
pagination: { limit: number; next_cursor: string | null };
};
type CorrectionMutationResult = CorrectionRecord & {
replayed?: boolean;
};
type CorrectionWriteOptions = {
workRunId: string;
correctionId?: string;
idempotencyKey: string;
expectedVersion?: number;
expectedWorkRunVersion?: number;
};
type CorrectionRequestOptions = RequestInit & {
expectedVersion?: number;
idempotencyKey?: string;
};
class RetvestProblemError extends Error {
constructor(
readonly status: number,
readonly category: CorrectionProblemCategory,
readonly problem: RetvestProblem,
readonly retryAfter: string | null
) {
super(safeProblemMessage(status, category));
}
}
const sdk = new RetvestClient({
baseUrl: mustEnv("RETVEST_API_BASE"),
apiKey: mustEnv("RETVEST_API_KEY")
});
const baseUrl = mustEnv("RETVEST_API_BASE").replace(/\/$/, "");
const apiKey = mustEnv("RETVEST_API_KEY");
void sdk;
function mustEnv(name: string) {
const value = process.env[name];
if (!value) throw new Error(`Missing ${name}`);
return value;
}
function correctionPath(workRunId: string, suffix = "") {
return `/admin/work-runs/${encodeURIComponent(workRunId)}/corrections${suffix}`;
}
function correctionProblemCategory(problem: RetvestProblem): CorrectionProblemCategory {
return (
problem.category ??
problem.code ??
problem.type?.split(/[/:#]/).at(-1) ??
"unknown_problem"
) as CorrectionProblemCategory;
}
function safeProblemMessage(status: number, category: CorrectionProblemCategory) {
if (category === "validation_failed") return "Correction payload needs review.";
if (category === "version_conflict") return "Correction state changed; refresh before retrying.";
if (category === "already_finalized") return "Correction already has a terminal decision.";
if (category === "forbidden") return "Correction action is not permitted for this actor.";
if (category === "tenant_mismatch") return "Correction is unavailable for this scope.";
if (category === "rate_limited") return "Correction request was rate limited.";
if (category === "unavailable") return "Correction service is temporarily unavailable.";
if (category === "timeout") return "Correction request timed out; confirm the ledger state.";
if (category === "idempotency_conflict") return "Idempotency key was reused with a different body.";
if (category === "invalid_transition") return "Correction cannot move to that state.";
return `Correction request failed with status ${status}.`;
}
function retryAfterMillis(value: string | null) {
if (!value) return 1_000;
const seconds = Number(value);
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1_000);
const parsedDate = Date.parse(value);
if (Number.isFinite(parsedDate)) return Math.max(0, parsedDate - Date.now());
return 1_000;
}
function canRetry(problem: RetvestProblemError) {
return (
problem.status === 429 ||
problem.status === 503 ||
problem.status === 504 ||
problem.category === "rate_limited" ||
problem.category === "unavailable" ||
problem.category === "timeout"
);
}
async function correctionRequest<T>(path: string, options: CorrectionRequestOptions = {}) {
const headers = new Headers(options.headers);
headers.set("Authorization", `Bearer ${apiKey}`);
headers.set("Accept", "application/json, application/problem+json");
if (options.idempotencyKey) headers.set("Idempotency-Key", options.idempotencyKey);
if (options.expectedVersion !== undefined) {
headers.set("Expected-Version", String(options.expectedVersion));
}
const response = await fetch(`${baseUrl}${path}`, { ...options, headers });
if (!response.ok) {
const problem = (await response.json().catch(() => ({}))) as RetvestProblem;
const category = correctionProblemCategory(problem);
const retryAfter = response.headers.get("Retry-After") ?? problem.retry_after ?? null;
throw new RetvestProblemError(response.status, category, problem, retryAfter);
}
return (await response.json()) as T;
}
async function retryCorrectionWrite<T>(
operation: () => Promise<T>,
options: { idempotencyKey: string; maxAttempts?: number }
) {
const maxAttempts = options.maxAttempts ?? 3;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
return await operation();
} catch (error) {
if (!(error instanceof RetvestProblemError)) throw error;
if (!canRetry(error) || attempt === maxAttempts) throw error;
await new Promise((resolve) => setTimeout(resolve, retryAfterMillis(error.retryAfter)));
}
}
throw new Error("unreachable correction retry state");
}
export async function createCorrection(options: CorrectionWriteOptions) {
return retryCorrectionWrite(
() =>
correctionRequest<CorrectionMutationResult>(correctionPath(options.workRunId), {
method: "POST",
idempotencyKey: options.idempotencyKey,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
correction_type: "claim_language",
original_summary: "The evidence pack is legally approved for filing.",
corrected_summary:
"The evidence pack is a starter export marked TEMPLATE - legal review required.",
reason: "The reviewed evidence supports export readiness, not legal approval.",
evidence_refs: [
{ type: "citation", label: "reviewed-citation-2" },
{ type: "gate", label: "legal-review-caveat" }
]
})
}),
{ idempotencyKey: options.idempotencyKey }
);
}
export async function listCorrections(workRunId: string, cursor?: string) {
const search = new URLSearchParams({ limit: "25" });
if (cursor) search.set("cursor", cursor);
return correctionRequest<CorrectionListResult>(
`${correctionPath(workRunId)}?${search.toString()}`
);
}
export async function applyCorrection(options: CorrectionWriteOptions) {
if (!options.correctionId) throw new Error("Missing correctionId");
if (options.expectedVersion === undefined) throw new Error("Missing expectedVersion");
return retryCorrectionWrite(
() =>
correctionRequest<CorrectionMutationResult>(
correctionPath(
options.workRunId,
`/${encodeURIComponent(options.correctionId)}/apply`
),
{
method: "POST",
idempotencyKey: options.idempotencyKey,
expectedVersion: options.expectedVersion,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
reviewer_note: "Reviewed evidence supports the narrower replacement claim."
})
}
),
{ idempotencyKey: options.idempotencyKey }
);
}
export async function rejectCorrection(options: CorrectionWriteOptions) {
if (!options.correctionId) throw new Error("Missing correctionId");
if (options.expectedVersion === undefined) throw new Error("Missing expectedVersion");
return retryCorrectionWrite(
() =>
correctionRequest<CorrectionMutationResult>(
correctionPath(
options.workRunId,
`/${encodeURIComponent(options.correctionId)}/reject`
),
{
method: "POST",
idempotencyKey: options.idempotencyKey,
expectedVersion: options.expectedVersion,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
rejection_reason_code: "unsupported_evidence",
reviewer_note: "Reviewed evidence does not support applying this correction."
})
}
),
{ idempotencyKey: options.idempotencyKey }
);
}
export async function retryCorrection(options: CorrectionWriteOptions) {
if (!options.correctionId) throw new Error("Missing correctionId");
if (options.expectedWorkRunVersion === undefined) {
throw new Error("Missing expectedWorkRunVersion");
}
return retryCorrectionWrite(
() =>
correctionRequest<CorrectionMutationResult>(
correctionPath(
options.workRunId,
`/${encodeURIComponent(options.correctionId)}/retry`
),
{
method: "POST",
idempotencyKey: options.idempotencyKey,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
expected_work_run_version: options.expectedWorkRunVersion,
decision_note: "Reviewer requested a follow-up correction before approval."
})
}
),
{ idempotencyKey: options.idempotencyKey }
);
}
Copy-Paste Calls
Use one idempotency key per user action. Reuse the same key only when retrying the exact same request body and expected version.
const workRunId = mustEnv("WORK_RUN_ID");
const correctionId = mustEnv("CORRECTION_ID");
const expectedVersion = Number(mustEnv("CORRECTION_EXPECTED_VERSION"));
const expectedWorkRunVersion = Number(mustEnv("WORK_RUN_EXPECTED_VERSION"));
await createCorrection({
workRunId,
idempotencyKey: "correction-wr-example-20260618-create-001"
});
const firstPage = await listCorrections(workRunId);
console.log(
firstPage.items.map((item) => ({
correctionId: item.correction_id,
sequence: item.correction_sequence,
status: item.correction_status,
receiptType: item.receipt_type,
rejectionReasonCode: item.rejection_reason_code
}))
);
await applyCorrection({
workRunId,
correctionId,
expectedVersion,
idempotencyKey: "correction-wr-example-20260618-apply-001"
});
await rejectCorrection({
workRunId,
correctionId,
expectedVersion,
idempotencyKey: "correction-wr-example-20260618-reject-001"
});
await retryCorrection({
workRunId,
correctionId,
expectedWorkRunVersion,
idempotencyKey: "correction-wr-example-20260618-retry-001"
});
Expected-Version And Refresh
Apply and reject calls should carry the last correction sequence or version that
the reviewer inspected. Retry request calls should carry the
expected_work_run_version from the Work Run state the reviewer inspected. This
example uses the Expected-Version header through expectedVersion. If the
platform returns a version conflict, refresh the ledger, show the latest
pending, applied, rejected, or superseded state, and ask the
reviewer to choose again.
try {
await applyCorrection({
workRunId: mustEnv("WORK_RUN_ID"),
correctionId: mustEnv("CORRECTION_ID"),
expectedVersion: Number(mustEnv("CORRECTION_EXPECTED_VERSION")),
idempotencyKey: "correction-wr-example-20260618-apply-002"
});
} catch (error) {
if (
error instanceof RetvestProblemError &&
(error.category === "version_conflict" || error.status === 409)
) {
const refreshed = await listCorrections(mustEnv("WORK_RUN_ID"));
console.log(
refreshed.items.map((item) => ({
correctionId: item.correction_id,
sequence: item.correction_sequence,
status: item.correction_status
}))
);
} else {
throw error;
}
}
Python Helper
For environments that cannot import retvest_client, operator scripts can keep
source-only helpers in Python. This Python example keeps typed RFC7807 parsing
and retry boundaries for safe replays only.
from __future__ import annotations
import os
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, Literal, Optional, TypeAlias
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen
import json
ProblemCategory: TypeAlias = Literal[
"validation_failed",
"version_conflict",
"already_finalized",
"forbidden",
"tenant_mismatch",
"rate_limited",
"unavailable",
"timeout",
"idempotency_conflict",
"invalid_transition",
"unknown_problem",
]
@dataclass
class CorrectionProblem:
status: int
type: Optional[str] = None
title: Optional[str] = None
detail: Optional[str] = None
category: Optional[str] = None
code: Optional[str] = None
instance: Optional[str] = None
retry_after: Optional[str] = None
@property
def parsed_category(self) -> ProblemCategory:
raw = self.category or self.code or self.type.rsplit(":", 1)[-1].rsplit("/", 1)[-1] if self.type else None
if raw in {"validation_failed", "version_conflict", "already_finalized", "forbidden", "tenant_mismatch", "rate_limited", "unavailable", "timeout", "idempotency_conflict", "invalid_transition"}:
return raw
return "unknown_problem"
class RetvestProblemError(RuntimeError):
def __init__(self, status: int, problem: CorrectionProblem, retry_after: Optional[str] = None):
self.status = status
self.problem = problem
self.retry_after = retry_after
super().__init__(problem.title or f"correction request failed with status {status}")
def _env(name: str) -> str:
value = os.getenv(name)
if not value:
raise RuntimeError(f"Missing {name}")
return value
def correction_path(work_run_id: str, suffix: str = "") -> str:
base = f"/admin/work-runs/{quote(work_run_id, safe='')}/corrections"
return f"{base}{suffix}"
def parse_retry_after(value: Optional[str]) -> float:
if not value:
return 1.0
if value.isdigit():
return max(0.0, float(value))
parsed = time.strptime(value, "%a, %d %b %Y %H:%M:%S GMT")
return max(0.0, time.mktime(parsed) - time.time())
def is_retryable(error: RetvestProblemError) -> bool:
return (
error.status in {429, 503, 504}
or error.problem.parsed_category in {"rate_limited", "unavailable", "timeout"}
)
def correction_request(
path: str,
method: str = "GET",
*,
expected_version: Optional[int] = None,
idempotency_key: Optional[str] = None,
body: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
base_url = _env("RETVEST_API_BASE").rstrip("/")
api_key = _env("RETVEST_API_KEY")
request = Request(
url=f"{base_url}{path}",
method=method,
headers={
"Authorization": "Bearer " + api_key,
"Accept": "application/json, application/problem+json",
},
data=json.dumps(body).encode("utf-8") if body is not None else None,
)
if body is not None:
request.add_header("Content-Type", "application/json")
if idempotency_key:
request.add_header("Idempotency-Key", idempotency_key)
if expected_version is not None:
request.add_header("Expected-Version", str(expected_version))
try:
with urlopen(request) as response:
payload = response.read().decode("utf-8")
return json.loads(payload) if payload else {}
except HTTPError as err:
raw_body = err.read().decode("utf-8") if err.fp else "{}"
response_json = json.loads(raw_body or "{}")
problem = CorrectionProblem(
status=int(err.code),
type=response_json.get("type"),
title=response_json.get("title"),
detail=response_json.get("detail"),
category=response_json.get("category"),
code=response_json.get("code"),
instance=response_json.get("instance"),
retry_after=response_json.get("retry_after"),
)
raise RetvestProblemError(
status=int(err.code),
problem=problem,
retry_after=err.headers.get("Retry-After"),
) from None
def retry_correction_write(
op: Callable[[], Dict[str, Any]],
idempotency_key: str,
max_attempts: int = 3,
) -> Dict[str, Any]:
for attempt in range(1, max_attempts + 1):
try:
return op()
except RetvestProblemError as error:
if not is_retryable(error) or attempt == max_attempts:
raise
delay = parse_retry_after(error.retry_after)
time.sleep(delay)
raise RuntimeError("retry state exhausted")
def create_correction(work_run_id: str, idempotency_key: str) -> Dict[str, Any]:
return retry_correction_write(
lambda: correction_request(
correction_path(work_run_id),
method="POST",
idempotency_key=idempotency_key,
body={
"correction_type": "claim_language",
"original_summary": "The evidence pack is legally approved for filing.",
"corrected_summary": "The evidence pack is a starter export marked TEMPLATE - legal review required.",
"reason": "The reviewed evidence supports export readiness, not legal approval.",
"evidence_refs": [{"type": "gate", "label": "legal-review-caveat"}],
},
),
idempotency_key=idempotency_key,
)
def list_corrections(work_run_id: str, cursor: Optional[str] = None) -> Dict[str, Any]:
query = "?limit=25"
if cursor:
query = f"{query}&cursor={quote(cursor, safe='')}"
return correction_request(f"{correction_path(work_run_id)}{query}")
def create_examples() -> None:
work_run_id = _env("WORK_RUN_ID")
create_correction(work_run_id=work_run_id, idempotency_key="correction-wr-example-20260618-create-001")
corrections = list_corrections(work_run_id)
print([row["correction_status"] for row in corrections.get("items", [])])
# For apply/reject/retry examples, confirm inspected versions and handle
# version-conflict/invalid-transition through a fresh ledger read.
first = corrections.get("items", [{}])[0]
if "correction_id" in first and first.get("correction_status") == "pending":
try:
correction_request(
correction_path(work_run_id, f"/{quote(first['correction_id'])}/apply"),
method="POST",
expected_version=first.get("correction_sequence"),
idempotency_key="correction-wr-example-20260618-apply-001",
body={"reviewer_note": "Reviewed evidence supports the narrower replacement claim."},
)
except RetvestProblemError as exc:
if exc.problem.parsed_category in {"version_conflict", "invalid_transition", "already_finalized"}:
raise RuntimeError("refresh correction ledger before retrying operator decision") from exc
raise
Typed Problem Handling
Do not print raw Problem detail, request bodies, idempotency keys, or customer
evidence. Branch on status and bounded category only.
| Problem state | Safe branch |
|---|---|
validation_failed or 422 |
Preserve draft inputs locally, show validation guidance, and use a new key if the body changes. |
version_conflict or stale 409 |
Refresh correction history before retrying apply or reject. |
already_finalized |
Show the terminal correction state and do not send another review decision for that correction. |
forbidden or 403 |
Disable the action for this actor and do not reveal restricted correction text. |
tenant_mismatch or unavailable 404 |
Show an unavailable state and do not reveal whether another tenant's Work Run exists. |
rate_limited or 429 |
Respect Retry-After for reads or exact idempotent replays. |
unavailable or 503 |
Retry reads or exact idempotent writes after Retry-After. |
timeout or 504 |
Retry the same idempotency key and expected version, then refresh the ledger. |
idempotency_conflict |
Stop retrying; ask the reviewer whether this is a new correction action. |
Related Docs
- Create Work Run corrections for a concise raw HTTP and source-only SDK create page.
- List Work Run corrections for pagination, request id, retry-after, and typed Problem handling.
- Apply Work Run corrections and Reject Work Run corrections for expected-version handling and unsafe review retry boundaries.
- Request retry for Work Run corrections for
retry-created pending rows,
expected_work_run_version, and approval/export gate examples. - Correction API Problem matrix for fixture-aligned operation Problem variants.
- Correction API retry metadata for request IDs, cursor pagination, Retry-After handling, and unsafe retry boundaries.
- Recording corrections for workflow boundaries, ledger reads, audit reads, and metadata-only examples.
- SDKs and CLI for current source package names and package distribution status.
- API reference for OpenAPI publication status.