@toloka-platform/sdk 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/validate.ts CHANGED
@@ -212,15 +212,197 @@ const examIssues = (settings: HumanWorkSettings, prefix: string): PipelineGraphV
212
212
  return issues;
213
213
  };
214
214
 
215
+ type Training = HumanWorkSettings['onboarding'];
216
+ type TrainingBlock = NonNullable<Training['steps'][number]['blocks']>[number];
217
+ type TrainingExamples = Extract<TrainingBlock, { type: 'examples' }>;
218
+
219
+ const isBlank = (value: string | undefined) => (value ?? '').trim() === '';
220
+
221
+ const quizIssues = ({ questions: [question] }: Extract<TrainingBlock, { type: 'quiz' }>, path: string) => {
222
+ if (question === undefined) return [{ path: `${path}/questions`, reason: 'Question text is required' }];
223
+ const questionPath = `${path}/questions/0`;
224
+ const issues: PipelineGraphValidationIssue[] = [];
225
+ if (isBlank(question.question)) {
226
+ issues.push({ path: `${questionPath}/question`, reason: 'Question text is required' });
227
+ }
228
+ if (question.options.length < 2) {
229
+ issues.push({ path: `${questionPath}/options`, reason: 'At least 2 options are required' });
230
+ } else if (question.options.some(({ label }) => isBlank(label))) {
231
+ issues.push({ path: `${questionPath}/options`, reason: 'Option label is required' });
232
+ }
233
+ const correctAnswers = [question.correctAnswer].flat().filter((answer) => answer !== '');
234
+ if (correctAnswers.length === 0) {
235
+ issues.push({ path: `${questionPath}/correctAnswer`, reason: 'At least one correct answer must be selected' });
236
+ } else if (correctAnswers.some((answer) => !question.options.some(({ value }) => value === answer))) {
237
+ issues.push({ path: `${questionPath}/correctAnswer`, reason: 'Correct answer must be one of the options' });
238
+ }
239
+ return issues;
240
+ };
241
+
242
+ type TrainingExampleCheck = TrainingExamples['examples'][number]['checks'][number];
243
+
244
+ const exactCheckIssues = (
245
+ { path: checkPath, golden }: Extract<TrainingExampleCheck, { type: 'exact' }>,
246
+ path: string,
247
+ ): PipelineGraphValidationIssue[] => [
248
+ ...(isBlank(checkPath) ? [{ path: `${path}/path`, reason: 'Check path is required' }] : []),
249
+ ...(golden === undefined || golden === null || (typeof golden === 'string' && isBlank(golden))
250
+ ? [{ path: `${path}/golden`, reason: 'Check golden is required' }]
251
+ : []),
252
+ ];
253
+
254
+ const exampleCheckIssues = (check: TrainingExampleCheck, path: string): PipelineGraphValidationIssue[] => {
255
+ const issues: PipelineGraphValidationIssue[] = check.type === 'exact' ? exactCheckIssues(check, path) : [];
256
+ if (check.type === 'code' && isBlank(check.code)) {
257
+ issues.push({ path: `${path}/code`, reason: 'Check code is required' });
258
+ }
259
+ if (check.type === 'llm') {
260
+ if (check.paths.every(isBlank)) issues.push({ path: `${path}/paths`, reason: 'Check paths are required' });
261
+ if (isBlank(check.criteria)) issues.push({ path: `${path}/criteria`, reason: 'Check criteria is required' });
262
+ }
263
+ if (check.type !== 'llm' && isBlank(check.hint)) {
264
+ issues.push({ path: `${path}/hint`, reason: 'Check hint is required' });
265
+ }
266
+ return issues;
267
+ };
268
+
269
+ const examplesIssues = ({ examples }: TrainingExamples, path: string): PipelineGraphValidationIssue[] =>
270
+ examples.length === 0
271
+ ? [{ path: `${path}/examples`, reason: 'An examples block must have at least one example' }]
272
+ : examples.flatMap(({ checks }, exampleIndex) => {
273
+ const examplePath = `${path}/examples/${exampleIndex}`;
274
+ return checks.length === 0
275
+ ? [{ path: `${examplePath}/checks`, reason: 'An example must have at least one check' }]
276
+ : checks.flatMap((check, checkIndex) => exampleCheckIssues(check, `${examplePath}/checks/${checkIndex}`));
277
+ });
278
+
279
+ const practiceIssues = (
280
+ { content, validators }: Extract<TrainingBlock, { type: 'practice' }>,
281
+ path: string,
282
+ ): PipelineGraphValidationIssue[] => [
283
+ ...(isBlank(content?.[0]?.value) ? [{ path: `${path}/content`, reason: 'Task description is required' }] : []),
284
+ ...(isBlank(validators?.[0]?.criteria)
285
+ ? [
286
+ {
287
+ path: `${path}/validators/0/criteria`,
288
+ reason: 'LLM instruction is required: an LLM grades every practice answer against validators[0].criteria',
289
+ },
290
+ ]
291
+ : []),
292
+ ];
293
+
294
+ const trainingBlockIssues = (block: TrainingBlock, path: string): PipelineGraphValidationIssue[] => {
295
+ switch (block.type) {
296
+ case 'info':
297
+ return [];
298
+ case 'text':
299
+ return isBlank(block.content?.[0]?.value) ? [{ path: `${path}/content`, reason: 'Content is required' }] : [];
300
+ case 'consent':
301
+ return isBlank(block.consentLabel) ? [{ path: `${path}/consentLabel`, reason: 'Consent label is required' }] : [];
302
+ case 'practice':
303
+ return practiceIssues(block, path);
304
+ case 'quiz':
305
+ return quizIssues(block, path);
306
+ case 'examples':
307
+ return examplesIssues(block, path);
308
+ }
309
+ };
310
+
311
+ const trainingIssues = (settings: HumanWorkSettings, prefix: string): PipelineGraphValidationIssue[] => {
312
+ const { onboarding, ui } = settings;
313
+ if (!onboarding.enabled || isSynthetic(settings)) return [];
314
+ const path = `${prefix}/onboarding`;
315
+ const issues = (['role', 'goal', 'successCriteria'] as const)
316
+ .filter((key) => isBlank(onboarding.info[key]))
317
+ .map((key) => ({ path: `${path}/info/${key}`, reason: `info.${key} is required` }));
318
+ const { steps } = onboarding;
319
+ if (steps.length < graphRules.minTrainingSteps || steps.length > graphRules.maxTrainingSteps) {
320
+ issues.push({
321
+ path: `${path}/steps`,
322
+ reason: `Training must have ${graphRules.minTrainingSteps} to ${graphRules.maxTrainingSteps} steps`,
323
+ });
324
+ }
325
+ const blocks = steps.flatMap((step) => step.blocks ?? []);
326
+ const hasBlock = (type: TrainingBlock['type']) => blocks.some((block) => block.type === type);
327
+ if (!hasBlock('quiz')) {
328
+ issues.push({ path: `${path}/steps`, reason: 'Training must include at least one quiz block' });
329
+ }
330
+ if (hasBlock('practice') && hasBlock('examples')) {
331
+ issues.push({
332
+ path: `${path}/steps`,
333
+ reason: 'Training must use either a practice block or an examples block, not both',
334
+ });
335
+ }
336
+ if (hasBlock('examples') && ['', '<></>'].includes(ui.code.trim())) {
337
+ issues.push({ path: `${path}/steps`, reason: 'A Training examples block requires the task UI to be built first' });
338
+ }
339
+ return [
340
+ ...issues,
341
+ ...steps.flatMap(({ blocks: stepBlocks = [] }, stepIndex) => {
342
+ const stepPath = `${path}/steps/${stepIndex}`;
343
+ return stepBlocks.length === 0
344
+ ? [{ path: `${stepPath}/blocks`, reason: 'Step must have at least one block' }]
345
+ : stepBlocks.flatMap((block, blockIndex) => trainingBlockIssues(block, `${stepPath}/blocks/${blockIndex}`));
346
+ }),
347
+ ];
348
+ };
349
+
215
350
  const humanWorkIssues = ({ settings }: HumanWorkNode, prefix: string): PipelineGraphValidationIssue[] => [
216
351
  ...thresholdIssues(settings.qualityCriteria, prefix),
217
352
  ...qualityElementIssues(settings.qualityCriteria, prefix),
218
353
  ...humanQaIssues(settings, prefix),
219
354
  ...humanAudienceIssues(settings, prefix),
220
355
  ...examIssues(settings, prefix),
356
+ ...trainingIssues(settings, prefix),
221
357
  ];
222
358
 
223
- export type PlatformRuleIssue = PipelineGraphValidationIssue & { readonly node: string };
359
+ const SIZE_LIMITED_SETTINGS = new Set([
360
+ 'audienceAndPricing',
361
+ 'code',
362
+ 'conditions',
363
+ 'entities',
364
+ 'envVars',
365
+ 'exam',
366
+ 'fieldProxies',
367
+ 'instruction',
368
+ 'offboardingRules',
369
+ 'onboarding',
370
+ 'overlap',
371
+ 'qualityAssurance',
372
+ 'qualityCriteria',
373
+ 'ui',
374
+ ]);
375
+
376
+ const textLength = (value: unknown): number =>
377
+ typeof value === 'string'
378
+ ? value.length
379
+ : typeof value === 'object' && value !== null
380
+ ? Object.values(value).reduce<number>((total, child) => total + textLength(child), 0)
381
+ : 0;
382
+
383
+ const SYNTHETIC_UNUSED_SETTINGS = new Set(['exam', 'onboarding']);
384
+
385
+ const settingSizeIssues = (node: Exclude<RuleNode, { type: 'root' }>, prefix: string) => {
386
+ const { settings } = node;
387
+ const unused = node.type === 'generation' && isSynthetic(node.settings) ? SYNTHETIC_UNUSED_SETTINGS : new Set();
388
+ const sizedSettings: [string, unknown][] = [
389
+ ['about/description', settings.about.description],
390
+ ...Object.entries(settings).filter(([setting]) => SIZE_LIMITED_SETTINGS.has(setting) && !unused.has(setting)),
391
+ ];
392
+ return sizedSettings.flatMap(([setting, value]) => {
393
+ const length = textLength(value);
394
+ return length > graphRules.nodeSettingMaxCharacters
395
+ ? [
396
+ {
397
+ path: `${prefix}/${setting}`,
398
+ reason: `This setting holds ${length} characters of text; the platform allows at most ${graphRules.nodeSettingMaxCharacters} in one node setting`,
399
+ },
400
+ ]
401
+ : [];
402
+ });
403
+ };
404
+
405
+ export type PlatformRuleIssue = PipelineGraphValidationIssue & { readonly node: string; readonly setting: string };
224
406
 
225
407
  export const platformRuleIssues = (graph: RuleGraph): PlatformRuleIssue[] => {
226
408
  const inUse = nodesInUse(graph);
@@ -230,8 +412,9 @@ export const platformRuleIssues = (graph: RuleGraph): PlatformRuleIssue[] => {
230
412
  const label = node.type === 'root' || node.settings.about.name === '' ? node.id : node.settings.about.name;
231
413
  return [
232
414
  ...nodeNameIssues(graph, node, prefix),
415
+ ...(node.type === 'root' ? [] : settingSizeIssues(node, prefix)),
233
416
  ...(node.type === 'generation' || node.type === 'quorum' ? humanWorkIssues(node, prefix) : []),
234
- ].map((issue) => ({ ...issue, node: label }));
417
+ ].map((issue) => ({ ...issue, node: label, setting: issue.path.slice(prefix.length + 1) }));
235
418
  });
236
419
  };
237
420
 
package/docs/authoring.md DELETED
@@ -1,320 +0,0 @@
1
- # Authoring
2
-
3
- How to express a pipeline project in TypeScript: fields, nodes, ports, and assembly.
4
-
5
- ## Source layout
6
-
7
- A project root is the directory holding `toloka.json` and `pipelines/`. Commands walk up from the working directory to find it.
8
-
9
- ```
10
- toloka.json CLI-managed identity state, never hand-edited
11
- fields.ts field declarations shared across nodes
12
- pipelines/
13
- cat-labeling/
14
- pipeline.ts default-exports definePipeline(...)
15
- nodes/
16
- collection/node.ts
17
- annotate-cats/node.ts
18
- ```
19
-
20
- One file per node keeps edits local: changing a prompt or a price touches one file, and a reviewer sees exactly which node changed. `pipeline.ts` holds the topology and nothing else.
21
-
22
- ## Declare fields once
23
-
24
- A field is a named data contract with a JSON Schema. Declare it once and import it wherever it is used.
25
-
26
- ```ts
27
- import { field } from "@toloka-platform/sdk";
28
-
29
- export const imageUrl = field("image_url", { type: "string", format: "uri" });
30
- export const annotations = field("annotations", {
31
- type: "array",
32
- items: { type: "object", additionalProperties: true },
33
- });
34
- ```
35
-
36
- The name is a bare identifier. When a field is a pipeline **input**, its name must match a column on the bound dataset, case-sensitively. Output-only and intermediate fields can be named freely.
37
-
38
- ## Node constructors
39
-
40
- Four work-node constructors take a name, settings, and optional `{ id }`: `code`, `generation`, `quorum`, and `match`. `root` is the single pipeline boundary and takes only settings plus optional `{ id }`.
41
-
42
- ### root
43
-
44
- Defines the pipeline's input and output contract. `started` is what each item carries in from the dataset; `completed` is what gets written back.
45
-
46
- ```ts
47
- import { optional, root } from "@toloka-platform/sdk";
48
-
49
- export const collection = root({
50
- started: [imageUrl],
51
- completed: [optional(annotations)],
52
- });
53
- ```
54
-
55
- Pass a bare field for a required binding. Use `optional(field)` for new optional bindings. The explicit `{ field, optional }` form remains supported and may appear in imported source.
56
-
57
- `root()` deliberately has no name argument: a pipeline has exactly one boundary, and its default wire id is `root`.
58
-
59
- ### code
60
-
61
- Deterministic work: transformations, HTTP calls, LLM calls. The Python program is an inline string.
62
-
63
- ```ts
64
- import { code } from "@toloka-platform/sdk";
65
-
66
- export const orderFaces = code("order_faces", {
67
- about: { name: "order_faces", description: "Sort annotations top-left to bottom-right." },
68
- envVars: [],
69
- input: [{ field: draftFaces, optional: false }],
70
- output: [{ field: faces, optional: false }],
71
- code: {
72
- code: `from main_types import Inputs, Outputs
73
-
74
- async def main(inputs: Inputs) -> Outputs:
75
- ordered = sorted(inputs["draft_faces"], key=lambda f: (f["boundingBox"]["y"], f["boundingBox"]["x"]))
76
- return {"faces": ordered}`,
77
- },
78
- });
79
- ```
80
-
81
- If the program calls an external service, list the secret names in `envVars`. The sandbox has no ambient environment.
82
-
83
- Register authored code behavior with `test.code(pipeline, node, name, callback)` from `@toloka-platform/sdk/testing`, execute its bound `run` helper, and cover representative inputs, boundaries, deterministic behavior, and real failures. Bare `runCodeNode` calls remain useful for exploratory tests but do not satisfy `toloka check` coverage.
84
-
85
- ### generation
86
-
87
- One human-work task type. The node owns the entire expert journey: instruction, UI, entity schemas, quality criteria, quality assurance, audience, pricing, Training, and Exam.
88
-
89
- Choose entity cardinality from the task, not from the component's JavaScript value shape. If one labeler produces one logical result, keep the entity static: omit `dynamic` and `maxEntities`, and use a path without `[*]`.
90
-
91
- ```ts
92
- {
93
- field: caption,
94
- entityType: "SHORT_ANSWER",
95
- jsonPath: "$.caption",
96
- description: "The one caption written for this image.",
97
- }
98
- ```
99
-
100
- Use `dynamic: true` only when one labeler produces multiple independent entities. Set `maxEntities` to a task-grounded upper bound rather than a generic default. A component may expose an array while still producing one logical entity; for a single upload or recording, keep a scalar field and static entity and select the completed first value with a path such as `$.video_file[0].downloadLink`.
101
-
102
- Entity types and labels are checked locally, for both generation and quorum nodes, before anything is sent to the platform:
103
-
104
- - `entityType` on every input and output entity must be one of the platform's core entity types. The list ships with the SDK in `src/core-entity-types.json`, generated from the server schema: `JUDGEMENT`, `EXPLANATION`, `PROMPT`, `USER_PROMPT`, `RESPONSE`, `RESPONSE_EVALUATION`, `RUBRIC`, `RUBRICS_GROUP`, `DIALOG`, `DIALOG_STEP`, `DIALOG_EVALUATION`, `SHORT_ANSWER`, `FEEDBACK`, `CONTEXT`, `IMAGE`, `ANNOTATION`, `SINGLE_LABEL`, `MULTI_LABEL`, `VIDEO`, `DOCUMENT`, `GOLDEN_SET`, `LOGS`, `SOLUTION`, `CODE`, `METADATA`, `AUDIO`, `AGENT_TRAJECTORY`, `MCP_SERVER`, `CONTAINER`, `CUSTOM`.
105
- - An output entity of type `SINGLE_LABEL` or `MULTI_LABEL` needs `allowedLabels` with at least two entries.
106
- - Every label `value` must be snake_case (`first_video`, not `firstVideo` or `First Video`).
107
-
108
- A violation is thrown as `PipelineGraphValidationError`, with one issue per offending path, as soon as the pipeline source is loaded — so `toloka check`, `toloka plan`, `toloka apply` and `toloka validate` all fail on it locally before any platform request.
109
-
110
- The following task is legitimately dynamic because the labeler can draw one independent box for every visible face:
111
-
112
- ```ts
113
- import { generation } from "@toloka-platform/sdk";
114
-
115
- export const annotateFaces = generation("annotate_faces", {
116
- about: { description: "Draw a box around every visible face.", projectType: "general" },
117
- publicName: "Face annotation",
118
- instruction: "Draw one tight rectangular box around every visible human face.",
119
- entities: {
120
- input: [{ field: imageUrl, entityType: "IMAGE", description: "Public URL of the image." }],
121
- output: [
122
- {
123
- field: draftFaces,
124
- entityType: "ANNOTATION",
125
- jsonPath: "$.draft_faces[*]",
126
- description: "One tight box per visible face.",
127
- dynamic: true,
128
- maxEntities: 50,
129
- },
130
- ],
131
- },
132
- qualityCriteria: [
133
- {
134
- id: "123e4567-e89b-42d3-a456-426614174000",
135
- qualityElement: "Completeness",
136
- thresholds: { pass: "Every visible face is boxed.", fail: "A visible face is missing." },
137
- targetEntity: draftFaces,
138
- },
139
- ],
140
- ui: {
141
- code: "<Field.ImageAnnotation path={'draft_faces'} image={actions.get('image_url', '')} tools={['rectangle']} />",
142
- data: '{"image_url":"https://example.com/face.jpg"}',
143
- preprocess: "return {}",
144
- postprocess: "return {};",
145
- constants: "{}",
146
- },
147
- audienceAndPricing: {
148
- audienceType: "human",
149
- verifiedExperts: true,
150
- audience: {
151
- languages: { type: "and", values: [{ value: "English" }] },
152
- specializations: { type: "and", values: [] },
153
- countries: { type: "or", values: [] },
154
- },
155
- pricePerTask: 0.2,
156
- timeForTask: 60,
157
- perExpertCapEnabled: false,
158
- perExpertCapValue: 1,
159
- },
160
- });
161
- ```
162
-
163
- To require a specialization, add `{ value, qualificationId }` entries to `audience.specializations.values`. Both come from the platform catalog — `toloka audience specialization list` — where `NAME` is the `value`, `ID` is the `qualificationId`, and `EXPERTS` tells you how large the pool is. Specializations require `verifiedExperts: true`.
164
-
165
- Test the interface locally before applying it. The SDK's Vitest fixture renders this exact `ui` block in Chromium, interacts with Fields by `path`, runs postprocess, validates output entities, and saves screenshots. See [Test pipelines locally](./testing.md).
166
-
167
- ### quorum
168
-
169
- The same item labeled by N independent people, with disagreement preserved. Every output field becomes a top-level array with one element per labeler.
170
-
171
- ```ts
172
- import { quorum } from "@toloka-platform/sdk";
173
-
174
- export const ratePair = quorum("rate_pair", {
175
- about: { name: "rate_pair" },
176
- publicName: "Rate the pair",
177
- overlap: 3,
178
- entities: {
179
- input: [{ field: pairUrl, entityType: "CONTEXT" }],
180
- output: [
181
- {
182
- field: verdict,
183
- entityType: "SINGLE_LABEL",
184
- allowedLabels: [
185
- { label: "First video", value: "first" },
186
- { label: "Second video", value: "second" },
187
- ],
188
- },
189
- ],
190
- },
191
- qualityCriteria: [],
192
- instruction: "Pick the better of the two videos.",
193
- ui: {
194
- code: "<View.Card><Field.RadioGroup path={'verdict'} label={'Better video'} options={[{ label: 'First video', value: 'first' }, { label: 'Second video', value: 'second' }]} validation={[{ required: true }]} /></View.Card>",
195
- data: "{}",
196
- preprocess: "return {}",
197
- postprocess: "return {};",
198
- constants: "{}",
199
- },
200
- onboarding: {
201
- enabled: true,
202
- steps: [
203
- {
204
- id: "step-1",
205
- blocks: [
206
- {
207
- id: "block-1",
208
- type: "text",
209
- content: [{ type: "markdown", value: "Watch both videos." }],
210
- },
211
- ],
212
- },
213
- ],
214
- info: {
215
- estimatedTime: "1 minute",
216
- role: "Rater",
217
- goal: "Rate the pair",
218
- successCriteria: "Submit a rating",
219
- },
220
- },
221
- });
222
- ```
223
-
224
- A quorum node **requires** an `onboarding` block: the Training course is part of the node, not an optional extra. The platform additionally requires at least three steps with at least one quiz block before the pipeline can deploy, which the type system does not enforce — a one-step placeholder compiles and applies but will not launch.
225
-
226
- ### match
227
-
228
- Predicate routing. Conditions are evaluated in declaration order. A condition's `logic` defaults to `'and'`, so every predicate must match; set `logic: 'or'` when any one predicate should match. `match()` writes the default into the graph, as the platform stores it, so `toloka plan` does not report the condition as changed after an apply.
229
-
230
- ```ts
231
- import { match } from "@toloka-platform/sdk";
232
-
233
- export const routeDisputed = match("route_disputed", {
234
- about: { name: "route_disputed" },
235
- conditions: [
236
- {
237
- name: "is_disputed",
238
- predicates: [{ field: verdict, jsonPath: "$", operator: "text_eq", value: "disputed" }],
239
- },
240
- ],
241
- input: [{ field: verdict, optional: false }],
242
- });
243
- ```
244
-
245
- Each condition name must be unique within the Match node and contain 2–32 characters. Start with a lowercase letter, use only lowercase letters, digits, and underscores, and end with a letter or digit. `match()` rejects invalid or duplicate names locally before any platform request.
246
-
247
- ## Connect ports
248
-
249
- `connect(from, to)` is the only way to create an edge. Ports are typed, so a wrong direction is a compile error.
250
-
251
- | node | ports |
252
- | ------------ | ------------------------------------------------- |
253
- | `root` | `started` (out), `completed` (in) |
254
- | `code` | `input` (in), `output` (out) |
255
- | `generation` | `input` (in), `output` (out) |
256
- | `quorum` | `input` (in), `output` (out) |
257
- | `match` | `input` (in), `matched(i)` (out), `default` (out) |
258
-
259
- ```ts
260
- connections: [
261
- connect(collection.started, annotateFaces.input),
262
- connect(annotateFaces.output, orderFaces.input),
263
- connect(orderFaces.output, collection.completed),
264
- connect(routeDisputed.matched(0), adjudicate.input),
265
- connect(routeDisputed.default, merge.input),
266
- ];
267
- ```
268
-
269
- The graph is acyclic. Review, retry, redo, Training, Exam, appeal, and payment retry are **settings inside the owning human-work node**, not extra nodes — there is no loop to draw.
270
-
271
- ## Assemble the project
272
-
273
- ```ts
274
- import { connect, definePipeline } from "@toloka-platform/sdk";
275
-
276
- export default definePipeline({
277
- dataset: "cat-images",
278
- fields: [imageUrl, annotations],
279
- nodes: [collection, annotateCats],
280
- connections: [
281
- connect(collection.started, annotateCats.input),
282
- connect(annotateCats.output, collection.completed),
283
- ],
284
- });
285
- ```
286
-
287
- `dataset` names the source dataset. `apply` creates it if it is absent, binds it to the pipeline, and records the resolved id in `toloka.json`.
288
-
289
- Leave `dataset` out for a pipeline that has no dataset yet, such as one created from a template in the platform UI. `plan` and `apply` then edit its graph without binding a dataset, and `toloka import` writes such a pipeline the same way. The pipeline cannot run until it has a dataset: add `dataset` to its source later, or bind one in the platform UI and import again. Apply never removes a bound dataset, so it refuses to apply a source that drops `dataset` from a pipeline that has one.
290
-
291
- Each `pipelines/<name>/pipeline.ts` is one pipeline. A project can hold several; each names its own dataset, and a dataset can be shared.
292
-
293
- Because assembly is ordinary TypeScript, a family of near-identical pipelines can be produced by a function that returns `definePipeline(...)`. The `connections` array stays literal and readable, which is the property worth protecting: topology should never be something a reader has to infer from a helper's implementation.
294
-
295
- ## Identity
296
-
297
- Constructors mint deterministic ids from the node name, so authored source needs no ids at all.
298
-
299
- `toloka import` emits explicit `{ id }` options for nodes and fields that already exist on the platform. **Preserve them.** They are how reconciliation recognizes the same resource instead of replacing it.
300
-
301
- Never hand-write `fp_…`, `ds.…`, `pl.…`, or `pp.…` values into settings, and never author a `layout` block: layout is not authored, existing nodes keep their canvas position, and the server places new nodes one column after their rightmost input and moves End to the right when they reach it.
302
-
303
- ## Validate
304
-
305
- ```sh
306
- toloka check
307
- toloka validate
308
- ```
309
-
310
- `definePipeline` and the typed ports add local declaration and connection invariants. `toloka check` also reports, as warnings, the platform rules that would reject a node connected to the root: node names, unique quality elements, quality-criterion thresholds, the minimum task and Human QA review times, a positive price per task, a media upload component on a human `data_collection` node, and the limits of an enabled exam. `toloka apply` refuses to write a new or changed pipeline that breaks them, before any platform write; an unchanged pipeline, such as a draft saved in the platform UI, does not block apply of the others. `toloka validate` posts each bound pipeline to `POST /pipelines/:pipelineId/graph/validate` and reports platform spec errors, warnings, and the latest matching check jobs. It does not write the graph.
311
-
312
- A pipeline that is not on the platform yet is skipped until `toloka apply` creates it. The published JSON contract is still available as `validate(graph)` for importer and fixture tests; that helper also runs the local entity checks described under [generation](#generation) and makes no network call.
313
-
314
- A successful validate is necessary, not sufficient for launch. Gates outside the graph contract — a Training course that is enabled but unbuilt, a task UI that was never validated — can still block deployment. See [limitations](./limitations.md).
315
-
316
- ## Next
317
-
318
- - [Nodes](./nodes.md) — choosing a node, and the price range it must stay within
319
- - [Datasets](./datasets.md) — columns and immutability
320
- - [CLI](./cli.md) — the reconcile loop