docs/PRODUCTION.md View source on GitHub

Production workflows

中文

Production projects pin a dataset version, a published label-set version and an optional annotation template. The output is another dataset version plus an ordinary annotation batch. Release reconciliation and datasheet facts consume the same version manifest and annotation metadata.

Objects and relationships

GET /api/ontology describes fourteen added object kinds: user, team, role, skill, label_set, template, project, task_package, production_task, assignment, annotation_revision, review, model, prelabel_run. The original worker task remains a separate identity. All objects use AssetRef; label-set identity includes its version. Team and skill edits feed team-tier skill dispatch; a skill's level (1–10) is what dispatch compares.

Projects contain packages, packages contain tasks, and tasks reference immutable revisions, assignments and reviews. Membership, role bindings, skills, assignment owners, review targets, previous revision pointers and pinned configuration use the shared ontology link vocabulary. Read authoritative projections with GET /api/production/objects/{kind}; optional filters are object_id, project_id, task_id, version, limit.

Six states and three tiers

State Meaning
pending Ready for annotation, including returned work
in_progress Annotation work has begun or was assigned
submitted An exact revision awaits review
in_review A reviewer has claimed the submitted task
approved An exact revision is approved for finalization
finalized That revision has entered a new dataset version

Rework returns a task to pending, increments its round and retains the original annotator; a manager may take a returned round back and assign it to someone else by name (see Dispatch). There is no automatic escalation; progress lists tasks with at least three rework rounds. Package and project status come from six counters updated in the same transaction as each task transition. They have no separate mutable status.

Tier Behavior
personal (default) Save/import, then submit directly to approved. No assignments or review rows; the action audit records SYSTEM_APPROVAL.
group Named assignment or self-claim, submit, review, return with issues, resubmit, approve. Self-review is allowed.
team Group rules plus enforced leases with heartbeats, a per-project dispatch strategy (assign, skill or claim), strict separation of annotator and reviewer, and P26 sampling acceptance of every package before finalization. See Team tier.

upgrade_project permits only forward transitions. Downgrading is rejected because completed review history cannot be reinterpreted as an earlier workflow. A second project participant produces suggest_review: true once in the relevant receipt. It never changes the tier automatically. Every assignment records a lease expiry; only team-tier projects enforce it (group and personal behavior is unchanged).

When a personal project upgrades, editable tasks with saved human work receive an annotation assignment for their existing author. The author can continue saving, submit for review or release the task through the normal holder checks, without reopening or incrementing the round. Task state and revision history are preserved; unowned tasks, model-only predictions and approved work receive no new assignment. Preserving historical ownership grants no role scopes and does not bypass current account authorization. After release, the author must claim or receive an assignment again.

Controlled writes

Each request has a required client-generated request_id. Prepare, inspect and execute through the existing action protocol. Actions always record audit, lineage and a durable receipt, including actions without an approval step.

Actions Approval
create_label_set, split_packages, assign_tasks, claim_task, release_task, heartbeat, save_revision, submit_task, review_task, reopen_task, revoke_assignment, configure_project (except below), upgrade_project, manage_users, manage_skills, import_predictions None
publish_label_set, create_project, register_model, update_model, define_role, update_role, accept_package, upgrade_project_template, finalize_project Human approval
run_prelabel Human approval if the frozen estimate exceeds the request budget: cloud models price tokens and images (see AI prelabel), other providers task count × unit price
configure_project lowering review_sample_rate Human approval
configure_project starting or widening high-confidence pass-through Human approval

create_label_set also manages template definitions with target: "template" and operation: "create" | "update" | "delete". User/team operations are under manage_users; skill operations are under manage_skills. The action schemas specify all fields, authorization scopes and bilingual examples.

Template versions. Every template write (create_label_set with target: "template", including archiving) appends an immutable version; both databases reject UPDATE and DELETE of saved versions. A project locks the template revision that is current when it is created (template_version), next to its published label_set_version. Saving, the submit check, the workbench form and finalization read those locked versions, so editing or archiving a shared template, or publishing a new label-set version, changes no existing project.

upgrade_project_template (production:manage, human approval; MCP and the Agent can only prepare it) moves one unfinalized project. template_version defaults to the template's newest revision and label_set_version to the newest published version; downgrades, archived targets and upgrades that change nothing are refused. The plan's project object carries template_upgrade:

  • from/to template and label-set versions;
  • labels added, removed, renamed (same identity, new name) and otherwise changed; attributes (target:key) added, removed, changed and newly required; other template settings that changed;
  • task_count: every task of the project (all of them switch versions);
  • annotated_task_count: tasks that have an existing annotation, which is the task's current (latest) revision; tasks without a revision are not counted. annotation_object_count counts the classification labels, boxes, polygons, skeleton instances, text spans and media segments in those revisions;
  • invalid_task_count and invalid_tasks: existing annotations that would fail the target versions' submit-time check (the same rules as submit_task: labels of the target label-set version, template components and count rules, required and typed attributes), each with every problem listed; invalid_object_count: objects whose own label or attributes fail.

The plan freezes the project and every task head, so a save, a newer template or a moved lock between preparing and signing voids it, and execution recomputes it. Signing changes only this project's template_version and label_set_version; revisions, task states and other projects stay as they were, and non-compliant annotations are fixed through the normal save and rework flow. Databases from v0.18.0 and earlier are migrated at startup: each template's current revision is recorded as a version and each project without a lock is locked to it, which is the version it was really using, so behaviour does not change; running the migration again writes nothing.

A repeated preparation with the same actor/action/request ID and identical input returns the original plan. Repeated successful execution returns its original run and receipt. Reusing the ID with changed input or caller limits is a conflict. A plan freezes the facts its decision depends on, and execution refuses it if they changed: per-task content actions (submit_task, review_task, reopen_task, release_task, heartbeat) freeze the whole task, its active assignments and the project; revoke_assignment and assign_tasks freeze only each task's state, round and current holders (assignment id, person and stage), so a holder's autosaves, a model draft import or a lease renewal between preparing and confirming do not void the reclaim or dispatch someone reviewed, while a submission, a round change or a new holder does. Acceptance and finalization keep freezing the exact approved revisions. A premature missing-approval attempt is audited and can be retried after signing. To correct failed inputs, use a fresh request ID. save_revision.previous_revision_id must equal the server head; HTTP 409 includes latest_revision. Both databases reject direct UPDATE and DELETE of revision history, and enforce one active assignment per task/stage with a unique partial index. Losing a claim selects the next available task.

Roles and identity

With zero registered users, authorization preserves local unrestricted behavior, including existing actions and evaluations. The first registered user receives the administrator template unless roles were explicitly supplied. Once any user is registered, unknown, disabled or archived actors have read-only authority; archiving the last user does not restore anonymous writes.

Effective scopes are the union of active global role bindings and bindings to the actual project. Caller-declared scopes only narrow this union. A project role cannot authorize another project's tasks, and a batch cannot mix projects. Claim/release use production:claim plus the stage's annotation or review permission; reviewers do not acquire annotation-edit permissions merely to claim review work.

Five editable templates are available: administrator, project_manager, annotator, reviewer, acceptance. Acceptance has no write scopes. project_manager also holds datasets:export for training splits and exports of finalized versions. Roles can use only registered action scopes, never * or invented scopes. Role plans list every allowed and denied action. Definitions and updates become effective only after human approval and execution; the signer's current grant ceiling is checked at both points. A separate authorized administrator may sign a role plan; the original actor executes it. Other action approval identity contracts remain unchanged. Asset applicants still cannot approve their own applications.

HTTP actor selection uses X-Datakeel-Actor after registration, and decision bodies must name that same actor. Legacy mutation routes enforce the corresponding server scope. Runtime session ownership is stored separately from the legacy conversation display actor, so a request cannot borrow a privileged Agent/workflow session. These names describe actors in a locally trusted installation; deployment-level authentication remains an independent boundary. See small-team deployment for the supported authenticating-proxy boundary and verification checklist.

MCP and Agent expose production reads and prepare-only writes. They cannot sign or execute production plans. Existing non-production reversible Agent behavior remains compatible. Humans use Web approval cards or explicit CLI/API calls.

Team tier

The team tier adds rules on top of the group tier; objects, states and actions are the same, and a group or personal project behaves exactly as before.

Leases. A claim or assignment is a lease of lease_minutes (default 10, per project, configure_project changes it). The holder renews it with heartbeat: the annotation workbench renews automatically while the task is open (see Open tasks refresh themselves), and the API, CLI or an MCP-prepared plan can renew it too. After the deadline every holder write (save_revision, submit_task, heartbeat, review_task) fails with an explicit "lease expired" conflict instead of succeeding silently; once reclaimed, the error says so. The reaper runs inside the existing worker loop (and as datakeel production reap [--now ISO] [--limit N]). It returns expired annotation work to pending and expired review work to submitted; saved revisions and the revision head are kept, so the next holder continues from them. A lease only runs while its stage is active, so an annotator's retained assignment is not reclaimed while the task waits for review, and a rework return gives it a fresh lease. Each release is one row in the append-only production_lease_releases table keyed by the assignment, and the reaper rereads the assignment under the task lock (FOR UPDATE SKIP LOCKED on PostgreSQL), so concurrent or repeated reaper processes release each lease exactly once and an interrupted pass can simply run again. Upgrading a group project to the team tier gives each open assignment a full lease from the upgrade moment; only the enforced deadline is set, the assignment records stay unchanged and the next heartbeat renews both. A reclaim record reports the enforced deadline.

Dispatch. dispatch_strategy is per project: assign (managers assign; self-claim is refused), skill (managers run assign_tasks with strategy: "skill"; self-claim requires the skill) or claim (self-claim, the default). All three write the same assignment table and the one-active-assignment unique index still applies; each assignment records its source in dispatch (assign, skill, claim or preserved). A skill requirement names an annotation type, a domain and min_level. A person qualifies when an active skill bound to them matches type and domain at that level or above; level is only a filter. Among qualified people with the stage permission, tasks are taken by priority (highest first) then task id, and each goes to the person with the lightest load of that stage in the project, ties broken by the smallest user id; the load counts each assignment as it is made, so a batch is reproducible. A person's load is their open work only: annotation assignments whose task is pending (including returned rework) or in progress, and review assignments in progress. Work submitted and waiting for review, or already approved, does not count, even though the annotation assignment stays until approval. Claims, named and skill dispatch, the cockpit's "N open now", the dispatch preview and skill_workload all use this one count. Self-claim and skill dispatch keep rework with its original annotator while that person is an active user; once the original annotator is disabled, skill dispatch may give the round to someone else. A manager can also take a returned round back (revoke_assignment) and assign it to another person by name: the prepared plan lists each handover in transfers (task, round, from the original annotator to the new one), the server fills this in and refuses execution if the handover changed in between, and the new person becomes this round's annotator (transferred_from on the assignment keeps the original). Review dispatch skips everyone who annotated the task in any round, so neither the original nor the new annotator can review it. max_active_tasks (project setting, or per request) caps each person's open work; a request may only use the project setting or a lower limit, and a higher one is refused with 422 naming the project setting: skill batches stop at the cap and list skipped tasks in unassigned with a reason, named batches above the cap are rejected whole (the error names the current load, how many the request adds and the cap), and claims at the cap are refused. Every path that checks a load first serializes on (project, person) for the rest of its transaction, so concurrent claims by one person, or claims racing a dispatch, cannot both count the same load.

Separation of duties. In the team tier nobody who annotated a task in any round reviews it: the current annotator, every author of a human revision and every past holder of its annotation assignment are excluded. The rule is checked when a review is claimed (the queue skips such tasks), assigned and recorded, so reassignment, a later role change or a reopen cannot launder it. Group projects still allow self-review.

Package acceptance. When every task of a package is approved, package_acceptance previews the P26 sample for it (method aql with aql, or ratio with ratio and acceptance_number, plus seed); the units are the package's samples, and lot, sample size, sample identities and decision numbers are computed by the same code path as P26 annotation_qa sampling. A person signs accept_package with one check per sampled unit (exactly the sample). The package is accepted when defective units do not exceed the acceptance number; otherwise every task in the package, sampled or not, returns to pending with its round increased by one and its original annotator. A team project finalizes only when every package's latest decision is an acceptance covering the current approved revisions, so reopening and re-approving a task requires a new acceptance.

Administration and rounds. revoke_assignment (scope production:assign, held by managers and administrators) returns an in-flight annotation or review stage to its queue, keeps revisions, and records the release with its reason. It works for any holder, including local assignments created before anyone registered. Submitted or approved work is reopened instead. reopen_task counts a rework round only when submitted or approved work is sent back; reopening a pending or in-progress task leaves its round, state, assignment and revisions as they are (design section 5), so it can still be revoked and assigned to someone else, who then sees it as ordinary round-0 work.

Reads. lease_status lists running leases by deadline split into live, expiring within expiring_within_seconds (default 120) and overdue, plus recent releases with their reason. Each listed assignment carries the deadline actually enforced; after a team upgrade restarted a lease this is the restarted deadline, not the stale recorded one. skill_workload sums open work (the load count above) and completed tasks per active skill. package_acceptance returns a package's status (in_progress, ready, accepted, rejected), progress, the sample preview when ready and its latest decision.

Roles. heartbeat (production:claim) is in the annotator and reviewer templates; configure_project and upgrade_project_template (production:manage), revoke_assignment (production:assign) and accept_package (production:accept) are in the project manager template; administrators hold every scope and the acceptance observer stays read-only. MCP and Agent may prepare these plans but never approve or execute them.

Labels, predictions and finalization

A label set version may carry written guidelines (overview and per-label rules in Chinese and English, with positive and negative examples citing sample ids) and, when drafted, its sources. Rules must name labels of the same version. draft_label_set drafts an unpublished version from data standards, existing annotations and sampled files; see Drafting a label set and guidelines.

Publish a draft label set to seal that version permanently. New versions declare a migration for every renamed or removed label: rename, delete, merge or split. Splits require manual review. Publishing does not rewrite historical revisions. Impact counts are exact current annotation instances (each classification label, box or span) in tasks of projects pinned to the old version; superseded historical revisions are excluded. A separate affected-revision count is reported. label_set_diff recomputes current impact rather than estimating from totals.

register_model supports fake, import and cloud. Only cloud makes network calls; see AI prelabel. Import files as text in files with filename, content, and optional exact sample identity/dimensions. COCO boxes are pixel xywh; YOLO rows are normalized class cx cy width height [confidence]. The internal representation is pixel xyxy. Category mapping resolves label identities/names explicitly; unmapped categories, out-of-bounds boxes, empty images and malformed files are reported per image/file while valid images continue. COCO result arrays need exact image identities or an explicit single-file sample binding, plus explicit category mapping. Model revisions retain name, version, average box confidence and previous-head identity. COCO images carrying the datakeel_sample_id extension written by Datakeel training exports bind to that exact sample first, so a finalized version exported as COCO imports back without renaming. YOLO exports use hashed label filenames; bind each label file with sample_id from the archive's MANIFEST.json and map class indexes from data.yaml.

Prediction bounds allow an absolute 1e-7 pixel rounding tolerance on all four edges, then clip accepted coordinates to the image. This absorbs floating-point conversion noise without scaling the allowance with image size; larger excursions and boxes with no positive area remain invalid.

Image imports read each image header and record the upright width and height (EXIF Orientation applied) in the manifest metadata, next to stored_width, stored_height and orientation; when the header cannot be read the sizes are recorded as null (unknown) and an unreadable orientation counts as 1. Predictions are stored in the upright frame: YOLO rows are normalized to the upright size (Ultralytics applies EXIF before training and inference). A COCO image whose width/height equal the upright size is upright; equal only to the stored size (a 90-degree orientation) means stored pixels, converted on import; a square image defaults to upright. A file's coordinate_frame: "display" | "stored" overrides this. YOLO without image_width/image_height uses the recorded size; when the image has no recorded size either, the whole import is refused with HTTP 422 naming the image and the prediction file. A complete COCO document supplies per-image dimensions in images. A multi-image COCO results array imports as one file: results are grouped by image_id, which must match a project sample ID or a unique filename (exporter sequence numbers are not matched by project order). Every group that matches no image is listed as unknown_image with the number of results not imported, and a matched image without a size as unknown_size; nothing is dropped silently.

Templates validate core boxes, polygons, skeleton keypoints, classification, media segments and text spans, including enabled component sets in component_config.components. A segment template is allowed alone or with classification, never with spatial/text components. Creating or upgrading a segment project first requires every locked audio/video source to have a positive readable media_probe.duration_ms and a browser-supported codec, including sources without revisions. Saves, submission, approval, package acceptance, finalization and native JSONL imports all revalidate that locked modality/probe, exact media_duration_ms and every integer-millisecond half-open boundary. Missing/zero/stale probes, unsupported codecs and source-duration drift fail explicitly; no browser-reported duration is saved. A keypoint template has one ordered, strongly typed keypoint_schema; legacy schema-less placeholders are read-only and cannot be used for new writes or projects. Supported validation rules are min_annotations and max_annotations, counting skeleton instances rather than individual points; single-label classification uses label_mode: "single". COCO keypoint import is explicitly refused in both training and prediction import paths, even when the annotation also has a bbox; use annotations_jsonl for native skeleton interchange.

Attribute fields. A template may define up to 50 typed attributes. Each field has a key (an identifier), name_zh and name_en, a type, a target, required and an optional default:

type Stored value Extra definition
boolean true / false —
enum one option value options (value, name_zh, name_en), at least one, distinct
multi_enum list of distinct option values options as above
number finite number (not a boolean) optional minimum, maximum
text string max_length (default 200, at most 2000)

target: "object" (default) applies the field to every box, polygon, skeleton instance, media segment and text span; target: "record" applies it to the annotation record, which is how classification work carries attributes. Keys are unique within a target, options and ranges must fit the type, and a default must itself be a valid value. The workbench renders these fields as a form; templates without fields keep the free-form attribute dictionary and earlier behavior.

Every human save_revision checks the fields against the project's locked template version: a wrong type or a missing required field fails with HTTP 422 naming the key and the position, for example Attribute "kind" is required on box 1, Attribute "count" on polygon 2 must be a number between 0 and 10 or Attribute "quality" is required on the record (positions count from 1). A missing key or null is missing; for a required field an empty multi_enum list or blank text is missing too. submit_task checks the head revision again, so a field that an upgrade made required after a save blocks submission until it is filled. Model revisions (imports and prelabels) are type-checked only, so a prediction never fails because a person has not filled a field yet. Keys a template does not define are kept unchanged. Editing and lossless training round trips are documented in the workbench guide.

Only approved tasks can finalize; team projects also need every package accepted. The transaction freezes their approved revisions, writes native annotations and exact annotation/label counts into the new manifest, imports an ordinary AnnotationBatch, updates counters and records the producing project in lineage. Input versions and historic revisions remain intact.

AI prelabel, confidence tiers and AI pre-review

Cloud models

register_model with provider: "cloud" registers an OpenAI-compatible vision endpoint; the first tested one is Alibaba Cloud Bailian (DashScope compatible mode). Capabilities are box and/or classification; a run fills the components that both the model and the template version the project is locked to enable. Example:

{"id": "qwen-flash", "name": "qwen3.5-flash", "version": "2026-10", "provider": "cloud",
 "capabilities": ["box"], "currency": "CNY",
 "cloud": {"base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1", "model": "qwen3.5-flash",
           "credential_env": "DASHSCOPE_API_KEY", "input_price": 0.0002, "output_price": 0.002}}
cloud field Default Meaning
base_url — HTTPS endpoint (plain HTTP only for loopback); user info, query and fragment are refused
model — Provider model name
credential_env, credential_source —, env The name of the environment variable, or of the system keychain account when credential_source is keychain (macOS security find-generic-password -a <name> -w)
input_price, output_price — Price per 1,000 tokens in the model's currency; unit_price on the model adds a per-image charge
coordinate_space normalized_1000 Model box coordinates on a 0–1000 grid, or pixel coordinates of the sent image
max_image_side, token_patch 1280, 32 Images are downscaled to this side; one image token per 32×32 tile
expected_output_tokens, max_output_tokens 160, 2048 Output length prior for estimates; reply cap
cross_check, confidence_source true, combined Also send the mirrored image; how object confidence is formed (see tiers)
request_parameters {"enable_thinking": false} Extra body fields; model, messages, temperature and token cap cannot be overridden

Only the credential's name is stored. The key is read when a run starts, sent only as the Authorization: Bearer header and never written to the database, logs, receipts, lineage or API responses; without it the action fails before any request. Requests use no proxy settings, no redirects and no retries.

Pixels and coordinates. The model sees exactly the workbench pixels: upright, with the EXIF Orientation applied like the canvas (task_content), downscaled and re-encoded as JPEG without metadata, so its drafts are display-frame revisions like everyone else's. Each image is sent twice in parallel, as is and mirrored left-right. Boxes are converted with the same coordinate function as image transcription, checked against the sent view, mirrored back and scaled to source pixels. Out-of-bounds, zero-area, unknown-label and malformed boxes are dropped and listed in the run's dropped with the reason. Replies that are a bare JSON list, use bbox_2d/bbox keys or were cut off keep every complete object.

Estimate and budget. Preparing run_prelabel freezes a prelabel_estimate object in the plan: images to send, input and output tokens per image, per-image and total price and an upper bound at the maximum reply length. Input tokens are the instruction (its UTF-8 length / 3.3 + 25, calibrated on Bailian) plus the image tiles (at least four, plus two marker tokens). Output tokens start at expected_output_tokens and move toward the measured mean of earlier successful calls of the same model, this project's calls first (the prior weighs as 20 calls). An estimate above the request budget needs approval. The budget remains a hard ceiling after approval: images go out in batches of up to four, and an image is admitted only while the measured spend plus its expected price (this run's measured average once one image is done) stays within budget. A stopped run records stopped with the sample it stopped before, completed and remaining images, spend, budget and the next image's expected price; work already done is kept.

Records and failures. Each run keeps every call's view, outcome, tokens, price and latency, token totals, the estimate, drops, skipped samples, thresholds and tiers; a reply without usage is priced at the estimate. The workbench project read adds prelabel_spend, the run, image, token and cost totals per model. Per-image failures — timeout, rate_limited, network_error, provider_error_<status>, invalid_response, image_unreadable, revision_rejected, task_changed — are listed with the image's file name (filename, the manifest's relative path) and sample_id while other images continue; provider bodies are never stored. Rerunning the same action only sends editable (pending or in-progress) tasks that have no draft from the same model name and version, so failed and unsent images are filled without paying twice. Tasks whose current revision a person saved are skipped as well: no call, no charge and no place in the estimate. The run lists them in human_edited_sample_ids and the estimate counts them in human_edited.

No lock while the model answers. Executing a cloud run_prelabel is synchronous for the caller but holds no transaction during model calls. The action's own transaction only checks the credential, claims the project's run slot, freezes targets, estimate and thresholds, and records the run as running (the action run is RUNNING without a receipt). After it commits, images go out in batches of four outside any transaction; each batch is written in its own short transaction that takes the same locks as a single-task action, re-reads and locks just those tasks, and skips a task that meanwhile got a draft from this model version or a newer head (code task_changed: the image is paid and listed, the person's work stays on top). A last short transaction marks the run completed, writes the audit lines and publishes the single receipt, so execute still returns the finished run. Only one cloud run may be running per project: a second start is refused with a conflict and never sends an image, so nothing is paid or written twice. A run silent for 10 minutes (its process died) is marked abandoned and its action run FAILED when the next run starts; a runner that finds its run abandoned writes nothing more and stops sending. The workbench project read returns prelabel_progress for the newest cloud runs: status, planned, completed and failed images, spend, budget and last update; the cockpit refreshes it every five seconds while a run is running. held_drafts says how many tasks only got a draft because someone held them. Measured with a 40-image run and a 0.6 s provider delay, another project's task open, save and submit kept a p95 of 3, 14 and 9 ms on SQLite and 22, 64 and 64 ms on PostgreSQL, with no errors. We chose this synchronous segmented form over a background worker so API, CLI and MCP callers keep one finished receipt and no new process is needed.

Prelabel accuracy

production_prelabel_accuracy compares every approved or finalized human revision with its nearest preceding model revision. Besides the exact-match fields it returns iou_50 and iou_75: model objects, human objects, true positives, precision, recall, F1, and the tasks (and share) where every object hit; and attribute_agreement among matched objects. Objects match one-to-one within one label, greedily from the highest IoU down, like COCO; a pair at IoU ≥ 0.5 (or 0.75) is a hit. Boxes use box IoU, polygons exact area IoU, text spans character-interval IoU, and a classification label set hits only when identical. Attribute differences never remove a geometric hit. The cockpit headline is F1 at IoU 0.5; hovering shows the rule, precision, recall and the 0.75 figures. Keypoints have no OKS/IoU implementation in this release: keypoint-only comparisons do not participate, their automatic accuracy/agreement is explicitly null, and the cockpit says Keypoint metrics: not supported yet rather than showing a synthetic perfect or zero score.

Confidence tiers

Each model object gets a confidence from confidence_source: self (the model's own probability), cross_check (the IoU of its same-label match in the mirrored reply) or combined (their mean, the default; it separated hits from misses best in the benchmark below). A task's tier is its lowest object's tier; a draft without objects is low. configure_project can set confidence_high and confidence_low (low ≤ high; clear: ["confidence_thresholds"] returns to measurement). Otherwise thresholds are measured on approved data. Each reviewed model object is a hit when it matches the approved human object at IoU ≥ 0.5 with the same label, and a non-decreasing confidence-to-hit-rate curve is fitted by isotonic regression (pool adjacent violators, implemented in confidence tiers): neighbouring confidence groups whose rate would fall are merged into one flat segment. High is the lowest confidence whose calibrated hit rate is at least 95%; low is the lowest confidence whose calibrated hit rate is at least 50%, and objects below it are low. When nothing reaches 50%, low is 1.0 with the note no_low_threshold. With fewer than 30 measured objects the defaults 0.85 and 0.5 apply with the note insufficient_samples, and pass_through is false. The workbench project read returns confidence_thresholds with the source, object count, each tier's measured hits and the curve's segments (confidence range, objects, hits and rate per segment).

After a run, untouched tasks of group and team projects that no one holds are routed by tier: high goes straight to submission, where AI pre-review and review sampling decide whether a person reviews it; medium keeps the draft for correction; low keeps the draft viewable but the workbench starts from an empty annotation. Personal projects only show the tier. A task someone holds, assigned or claimed and touched or not, or a rework round back with its annotator, only gets the draft in every tier: it is never passed through, its state and holder stay as they are, its tier records routed: "draft" with the note held, and the holder decides what to do with the draft. The run's held_drafts counts these tasks, and Prelabel runs shows "Held by someone, drafts only: N" for a cloud run. The run's tiers lists each task's tier, routing and draft revision.

Pass-through is answered for. A high draft is submitted directly only when the high threshold was measured or configured: while the defaults stand in (cold start), it is held as a draft with the note insufficient_samples and the workbench says that samples are still too few to pass through. A passed-through revision stays source: "model" and carries pass_through: model id, confidence, the high and low thresholds and their source and object count at that moment, and triggered_by, the person who ran the action. That person becomes the task's annotator, so in team projects separation keeps them from reviewing it, even after a manager takes the rework round back and hands it to someone else (group and personal tiers follow their usual rules), and a review row names them, never the reviewer. The action audit has one line per submission starting 模型高置信度直通 / Model high-confidence pass-through with the task, revision, model, confidence, thresholds and trigger. Starting or widening pass-through is a signed change. This covers a manual high threshold replacing cold-start defaults, or any bar lower than the one in force. Such a configure_project plan needs approval, and the audit line 放宽高置信度直通 / High-confidence pass-through relaxed names the old bar, the new bar and the signer. Raising the bar, or clearing back to defaults, needs no approval.

A model head is not submitted as a person's work. submit_task refuses (422) while the head revision is a model draft: the annotator first saves their own revision, changed or unchanged (for a low task the empty start, for a medium task the draft as confirmed). The workbench does that save itself when someone submits a draft without editing it.

AI pre-review on submission

Every submission is scored before anyone reviews it. The P26 suspicion rules run on the submitted head together with up to 500 other submitted, in-review, approved or finalized tasks of the project (near-duplicate images by perceptual hash), the locked template is rechecked, and a human head that departs from a confident model draft adds a disagreement reason (weight 0.5 × draft confidence × content difference). Each hit has a fixed weight; the risk is their noisy-OR, 1 − ∏(1 − weight), so it never falls when a reason is added. Risk ≥ 0.3 is high; every rule except rare_category (0.2) is high on its own. The score, each reason with its evidence and the boxes, polygons or spans it points to, the sampling draw and the decision are stored append-only against the exact submitted revision. Draft and near-duplicate comparisons look only at annotation kinds both sides recorded. A box-only model draft says nothing about the image's classification, but an empty list is a recorded "none" and still counts.

The review queue is ordered by risk, then rework round, model confidence and draft difference. review_sample_rate (default 1 = review everything, the previous behavior) controls low-risk sampling: a reproducible draw from the task, round and revision below the rate goes to review, otherwise the submission is approved and the action audit records AI 预审低风险,按抽检比例免审 / AI pre-review low risk, exempt by review sampling with the rate, risk and draw. High risk is always reviewed. Lowering the rate is a signed decision: a configure_project plan that lowers it needs approval. In personal projects the result is shown to the annotator and never blocks submission.

Benchmark on 50 COCO images (80 labels, both views; P/R at IoU 0.5 on images whose reply parsed):

Model F1@0.5 F1@0.75 Precision Recall Format failures CNY per image Median latency Confidence AUROC self / mirror / combined
qwen3.5-flash 0.560 0.420 0.704 0.464 1/50 0.0016 2.0 s 0.71 / 0.78 / 0.80
qwen3.5-plus 0.644 0.502 0.729 0.576 2/50 0.0046 3.6 s 0.75 / 0.81 / 0.82
qwen3.6-plus 0.522 0.404 0.667 0.429 7/50 0.0129 3.8 s 0.77 / 0.77 / 0.80

qwen3.7-flash returned HTTP 403 for this account. The format failures were cut-off or malformed replies that the current parser now partly recovers. qwen3.5-flash is the cheapest usable default; qwen3.5-plus is about 3× the price for about 15% higher F1.

CLI and REST

uv run datakeel production demo
uv run datakeel production prepare create_label_set labels.json --actor local
uv run datakeel production plan PLAN_ID --actor local
uv run datakeel production approve PLAN_ID --digest PLAN_DIGEST --actor local
uv run datakeel production execute PLAN_ID --digest PLAN_DIGEST --actor local
uv run datakeel production read project_progress project.json --actor local

The demo creates three generated images, published labels, a personal project and imported fake predictions. For personal work, use create_label_set → publish_label_set → create_project → split_packages → register_model → import_predictions → save_revision → submit_task → finalize_project. For group work, create/bind users with manage_users, set workflow_tier: "group", then use assign_tasks/claim_task → save_revision → submit_task → claim_task(stage=review)/review_task; a rework decision includes issues, and the original annotator saves and submits again before finalization. Sign only the steps listed in the approval table.

The workbench reads the same facts through a few HTTP reads under the same project and task grants: GET /api/production/workbench, GET /api/production/projects/{id}/workbench (page, view all/mine/review, package_id, and search, a case-insensitive substring of the sample's relative path or file name applied before paging; each listed task and every repeatedly reworked task is named in task_samples with its file name and relative path, which falls back to the file name), GET /api/production/projects/{id}/task-samples?task_id=… (file names and relative paths for up to 500 tasks of that project; other projects' identities are ignored), GET /api/production/tasks/{id}/workbench, and GET /api/production/tasks/{id}/status — a cheap poll that returns the task, its assignments, each running lease with the enforced expires_at, seconds_remaining and enforced, and the ten latest lease releases, without reading the source. Sample names come from the pinned version manifest's file name; server paths and object keys are never returned. In a team project the review view leaves out every task the caller annotated, by the same rule the review claim applies. POST /api/production/projects/{id}/dispatch-preview computes, without locking or writing, what assign_tasks with strategy: "skill" would do now: the qualified people, each task's pick, each person's current load and added count, and the unassigned tasks with their reason (task_state_not_dispatchable, already_assigned, load_limit_reached, no_qualified_person). It shares the matching code with execution; loads that change between preview and execution change the executed result, which the receipt reports.

REST equivalents are POST /api/actions/{action_type}/prepare, GET /api/actions/plans/{id}, POST /api/approvals/{id}, POST /api/actions/{id}/execute. Supply the returned digest for decisions. Read functions are available through POST /api/production/functions/{name} and through Agent/MCP: project_progress, package_status, annotator_workload, rework_rate, annotation_consistency, prelabel_confidence, label_set_diff, next_task, production_objects, production_prelabel_accuracy, and for the team tier lease_status, skill_workload, package_acceptance, and assignees (project_id, stage: who a manager can assign this stage's work to by name, with their open load; the same list as GET /api/production/projects/{id}/assignees, refused the same way when the caller cannot assign). Agreement reuses the existing annotation-quality evaluator; confidence counts all model revisions with recorded confidence. Rework rate is rework decisions divided by all review decisions per original annotator (rework_rate accepts optional window, days or explicit since/until UTC bounds, defaulting to all project reviews). production_prelabel_accuracy compares each approved/finalized human revision with its nearest preceding model revision, returning assessed tasks, exact matches and their rate (null without a reference), and the IoU precision, recall and F1 described under prelabel accuracy. Exact content includes attributes, duplicate shapes and reviewed-empty distinctions.

Implementation choices and sources

Choice Alternatives Reason and source
Transactional six-state counters Recount all tasks on each read; asynchronous cache Bounded progress reads and no stale cache window: task transitions, queries.
Append-only revisions and partial unique assignment index Mutable annotation row; application-only ownership checks Keep auditable history and enforce concurrent ownership in both databases: constraints.
Existing role/action scopes Separate authorization service/library One declared policy and audit source, no runtime dependency: registry, server authorization.
Typed local COCO/YOLO parser Add a format dependency; read arbitrary server paths Reuse existing pixel-coordinate convention with bounded input and per-file errors: legacy adapter, parsers.
Lease reaper inside the existing worker, one release row per assignment, task lock with SKIP LOCKED A separate scheduler process; per-assignment timers; PostgreSQL advisory locks; deleting expired rows No new process or dependency, crash-safe reruns and exactly-once release enforced by a primary key. Same visibility-timeout model as Amazon SQS and Kubernetes Leases; SKIP LOCKED as already used by the worker queue: reaper.
Skill match: level threshold, then least active load, then smallest user id Weighted score of level and load; global optimal matching (Hungarian, linear_sum_assignment); round robin A threshold mirrors MTurk qualification requirements (GreaterThanOrEqualTo), so level never trades against load; join-the-shortest-queue balancing is simple to explain and reproduce, needs no dependency and is exactly recomputable by an auditor: dispatch, rules.
Per-task actions skip the table-wide action lock on PostgreSQL; counters are written at commit in one sorted order Keep the global LOCK TABLE for every action; a per-project advisory lock; counter updates at each transition Measured with B8: the global lock capped throughput at 13 operations/s (save p95 4.4 s); a project lock would serialize one project the same way. Without it, counter rows written mid-transaction deadlocked a multi-task reaper against claims, so each transaction now applies its counter deltas once, sorted, just before commit, and the reaper commits each release separately. Task row locks and the unique assignment index keep these actions safe: locks, counters, CAPACITY.
Persist the task list's display order once per project (display_rank) and rank claims with one ordered SKIP LOCKED query Sort every open candidate in Python inside the claim transaction; order by random row identity; cache the order per project in memory The Python sort fetched and ordered up to 10,000 rows under SQLite's database-wide write lock, serializing every save behind each claim (B8 50-annotator save p95 2.8 s against a 200 ms target). Packages and the source version are immutable after the one-time split, so the order freezes at split time and legacy rows backfill idempotently on the first claim; the mixed-direction claim index walks the queue without a sort, and a claim still returns exactly the task the list shows as next: display order, claim, CAPACITY.
Every action takes its table-level locks before any row lock: per-task actions take ROW EXCLUSIVE on lineage_events (the only predicate table they write, for their receipt) up front Table-wide actions lock task rows (sorted) before their table locks; move the receipt out of the row-locked part; retry 40P01 once at the outer boundary A per-task action used to lock its task row and only then append its receipt, while a manager action held SHARE ROW EXCLUSIVE on lineage_events and waited for that row: a deadlock (HTTP 500). One global order (tables, then rows) removes the cycle, the standard prevention in the PostgreSQL deadlock notes; ROW EXCLUSIVE conflicts with SHARE ROW EXCLUSIVE but not with itself (conflict table), so annotators stay concurrent, as with intention locks (Gray, Lorie and Putzolu, Granularity of Locks in a Large Shared Data Base, VLDB 1975). Pre-locking rows needs every action's full row set in advance (project, package and member rows included) and breaks when one is missed; a receipt outside the transaction loses atomicity; a retry alone hides the cycle. B8 PostgreSQL 50 is unchanged: locks, CAPACITY.
Per-(project, person) transaction-level advisory lock before counting a load, taken in user-id order; the count refuses to run without it Lock the person's user row; a per-person counter row with a guarded update; SERIALIZABLE with retries; rely on the table lock Claims lock only the task they take, so two claims by one person both saw room under the cap. A transaction advisory lock needs no schema change, is released at commit or rollback and does not touch rows other actions update (user rows are rewritten by manage_users); a counter row needs a migration and every assignment end to keep it exact; SERIALIZABLE turns races into retry storms at 50 annotators. SQLite already serializes writers. Assertion-style checks of held locks follow the Linux lockdep_assert_held practice: load locks.
Template attribute fields: a typed list on the template (boolean, enum, multi_enum, number with range, text), applied to every shape or to the record, checked on save and submission CVAT per-label attributes (select, radio, checkbox, number as min;max;step, text; mutable, default_value); Label Studio control tags with required, perRegion and whenLabelValue; Labelbox radio, checklist and free-text classifications, global or nested under a tool; a free JSON Schema document The five types cover CVAT's input types (radio and select are one enum) and Labelbox's three classification kinds; target is Label Studio's perRegion choice. Bilingual names follow the interface languages. A closed typed list can be rendered as a keyboard form and checked with an error naming the key and shape, which arbitrary JSON Schema (composition, conditionals, references) cannot guarantee without a schema-to-form engine, a new dependency. Per-label applicability (CVAT, whenLabelValue) and frame-level mutability do not apply to single images today; they can be added as optional filters. Model drafts are type-checked only, matching a required field that a person, not a model, completes: model, save check.
Lock each project to a template version; a signed upgrade_project_template moves one project and states its exact effect Projects follow the shared template's current revision (the earlier behaviour); copy the template into each project; version the template but upgrade every project together A shared template edit must not change validation or forms under work already in progress, and one project's upgrade must not touch another. Versions are kept once per template and referenced, which the label set already does with label_set_version. Label Studio applies a changed labeling config to the whole project and checks it against existing annotations first (project API); CVAT warns that changing labels of a task with annotations can lose them (labels). Here the lock is explicit and the upgrade plan lists every non-compliant annotation before anyone signs: versions, plan.
Cloud prelabel over the OpenAI-compatible chat API with the existing httpx; Bailian qwen3.5-flash as the tested default Vendor SDKs (openai, dashscope) or a router such as LiteLLM; local models (out of scope); qwen3.5-plus, qwen3.6-plus, qwen3.7-flash One wire format reaches Bailian and most OpenAI-compatible servers with no new dependency, and a stub transport tests it offline. In the benchmark above flash is the cheapest usable model, plus gains about 15% F1 at 3× the price, 3.6-plus is slower, dearer and fails the format more often, and 3.7-flash is not open to this account. Prices and token rules: Bailian pricing, image tokens, OpenAI-compatible API, retirement; 0–1000 grid: Qwen3-VL grounding cookbook, Qwen3-VL report; published grounding scores: Qwen3.5-35B-A3B, Qwen3.5-397B-A17B: client, run.
Estimate from instruction length and image tiles, output tokens shrunk from a prior toward the model's measured calls, budget checked before every image A fixed price per image; a provider tokenizer; only the maximum-reply upper bound Measured on Bailian: a 1,438-byte instruction is 460 tokens, and replies run from about 50 tokens on sparse images to 317–411 on crowded COCO scenes, so a fixed prior can miss by 2×; averaging toward measured calls (an empirical-Bayes mean) fixes that without a tokenizer dependency. Rehearsal: a cold run cost 0.90 of its estimate, a warm rerun 1.05: estimate.
Accuracy by one-to-one greedy matching within a label, highest IoU first, P/R/F1 at IoU 0.5 and 0.75 pycocotools COCOeval (detections in score order, AP over recall points); optimal Hungarian matching; exact match only Drafts carry no reliable ranking score and the cockpit needs counts a manager can act on; COCO gives each detection, in score order, its best unmatched truth, and taking the best pair first never pairs a weaker overlap ahead of a stronger one. Values equal an independent numpy implementation: COCO detection evaluation, cocoeval.py, matching.
Object confidence as the mean of the model's own probability and its IoU agreement with the mirrored image Self-reported probability only; mirror agreement only; token log-probabilities; repeated sampling Combined separated hits from misses best on all three models (AUROC 0.80–0.82 against 0.71–0.77 self-reported). Verbalized confidence is overconfident (Xiong et al., ICLR 2024); agreement under a flip is test-time augmentation (Wang et al., 2019). Coordinate log-probabilities are not exposed by every model and do not measure placement; repeated sampling costs more than one mirrored call. The mirror can be switched off: cross-check.
Risk as the noisy-OR of fixed rule weights, high at 0.3 Weighted sum clipped to 1; maximum weight; a classifier trained on review outcomes Noisy-OR (Pearl, Probabilistic Reasoning in Intelligent Systems, 1988, §4.3) reads each reason as an independent chance of an error: bounded, never lower after another reason, and corroborating weak reasons add up, which a maximum ignores and a clipped sum saturates. A new project has no review outcomes to train on; the planted-error test puts at least 80% of plants in the riskiest fifth: risk.
Version plus existing annotation import A separate production-only export format Existing release and datasheet consumers retain their contracts: finalizer, annotation importer.

Generated regression fixtures cover both workflows, two-database claim races, independent read goldens, exact migration counts, partial prediction failure, immutable history, optimistic conflicts and role grant ceilings. The capacity benchmark measures reads and the complete prepare-plus-execute save path on 10,000-task projects.