From 3f2df5c05cf87fa008b995be5c22e3aebc352eed Mon Sep 17 00:00:00 2001 From: nikoraes Date: Tue, 20 Oct 2026 10:26:44 +0000 Subject: [PATCH] Update Konnektr Graph documentation --- content/docs/graph/developers/import-jobs.mdx | 307 ------------------ .../docs/graph/how-to-guides/import-jobs.mdx | 240 +++++++------- 2 files changed, 124 insertions(+), 423 deletions(-) delete mode 100644 content/docs/graph/developers/import-jobs.mdx diff --git a/content/docs/graph/developers/import-jobs.mdx b/content/docs/graph/developers/import-jobs.mdx deleted file mode 100644 index 91d7618..0000000 --- a/content/docs/graph/developers/import-jobs.mdx +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: Import Jobs -icon: Upload -description: How the ND-JSON import job system works — streaming ingestion with checkpoint-based resumption, distributed locking, and automatic recovery. ---- - -The import job system ingests graph data (models, twins, relationships) from ND-JSON streams into Apache AGE. It supports checkpoint-based resumption, distributed locking, graceful cancellation, and automatic recovery. - -## Architecture - -``` -┌─────────────────────────────────────────────────┐ -│ API Endpoints (ImportJobEndpoints.cs) │ -│ PUT /jobs/imports/{id} │ -│ GET /jobs/imports/{id} │ -│ POST /jobs/imports/{id}/cancel │ -│ POST /jobs/imports/{id}/resume │ -└──────────────┬──────────────────────────────────┘ - │ -┌──────────────▼──────────────────────────────────┐ -│ AgeDigitalTwinsClient.Jobs.cs │ -│ ImportGraphAsync / ResumeImportJobAsync │ -└──────────────┬──────────────────────────────────┘ - │ -┌──────────────▼──────────────────────────────────┐ -│ StreamingImportJob (ImportJob.cs) │ -│ ExecuteWithCheckpointAsync │ -│ ┌────────────┐ ┌──────────┐ ┌───────────────┐ │ -│ │ Models │ │ Twins │ │ Relationships │ │ -│ │ (all at │ │ (batched │ │ (batched │ │ -│ │ once) │ │ 50) │ │ 50) │ │ -│ └────────────┘ └──────────┘ └───────────────┘ │ -└──────────────┬──────────────────────────────────┘ - │ -┌──────────────▼──────────────────────────────────┐ -│ JobService (JobService.cs) │ -│ - Distributed locking │ -│ - Checkpoint save/load/clear │ -│ - CRUD on {graphName}_jobs.jobs table │ -└──────────────┬──────────────────────────────────┘ - │ -┌──────────────▼──────────────────────────────────┐ -│ JobResumptionService (BackgroundService) │ -│ - Polls every 2 min for interrupted jobs │ -│ - Acquires lock, opens blob streams, resumes │ -└─────────────────────────────────────────────────┘ -``` - -## File Map - -| File | Role | -| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -| `src/AgeDigitalTwins/Jobs/ImportJob.cs` | Core streaming engine: `StreamingImportJob.ExecuteWithCheckpointAsync()` | -| `src/AgeDigitalTwins/Jobs/ImportJobCheckpoint.cs` | `ImportJobCheckpoint` model, `CurrentSection` enum | -| `src/AgeDigitalTwins/Jobs/ImportJobOptions.cs` | Config: batch size, checkpoint interval, heartbeat interval | -| `src/AgeDigitalTwins/Jobs/JobService.cs` | `JobService` — persistence, distributed locking, checkpoint CRUD | -| `src/AgeDigitalTwins/Jobs/JobLockInfo.cs` | Lock state model | -| `src/AgeDigitalTwins/Jobs/PositionTrackingStreamReader.cs` | Stream reader tracking 1-based line numbers for checkpoint seeks | -| `src/AgeDigitalTwins/AgeDigitalTwinsClient.Jobs.cs` | Public API surface on the SDK client | -| `src/AgeDigitalTwins/Models/JobRecord.cs` | Job record model with smart properties (reads from checkpoint during execution, results on completion) | -| `src/AgeDigitalTwins/Models/JobStatus.cs` | Enum: `Notstarted`, `Running`, `Succeeded`, `PartiallySucceeded`, `Failed`, `Cancelled`, `Cancelling` | -| `src/AgeDigitalTwins/Models/JobError.cs` | Error model with `Code`, `Message`, `InnerError`, `Details` | -| `src/AgeDigitalTwins.ApiService/Extensions/ImportJobEndpoints.cs` | REST API endpoint mappings | -| `src/AgeDigitalTwins.ApiService/Services/JobResumptionService.cs` | `BackgroundService` for automatic job recovery | -| `src/AgeDigitalTwins.ApiService/Models/ImportJob.cs` | API response DTO | -| `src/AgeDigitalTwins.ApiService/Models/ImportJobRequest.cs` | API request DTO (`inputBlobUri`, `outputBlobUri`) | - -## Job Lifecycle (State Machine) - -``` -Notstarted ──► Running ──► Succeeded - │ ├── PartiallySucceeded (errors > 0, but some items succeeded) - │ └── Failed (errors > 0, nothing succeeded) - │ - ├──► Cancelling ──► Cancelled - │ (heartbeat timer detects - │ DB status == Cancelling, - │ triggers CancellationTokenSource.Cancel()) - │ - └──► Running (keeps Running on DB - connectivity loss — resumed later) -``` - -Key transitions: - -- **Notstarted → Running**: When background `Task.Run` starts, or immediately for synchronous execution -- **Running → Cancelling**: Set by `CancelImportJobAsync()` via `UpdateJobStatusAsync(jobId, Cancelling)` -- **Cancelling → Cancelled**: Heartbeat timer (30s) polls DB, sees `Cancelling`, calls `combinedCts.Cancel()` -- **Running → Running** (stays): On `DatabaseConnectivityException` — keeps status, allows resumption -- **Running → Succeeded/PartiallySucceeded/Failed**: `DetermineFinalJobStatus()` after stream is fully consumed - -## ND-JSON Input Format - -Strictly ordered section markers, one JSON object per line: - -```jsonl -{"Section": "Header"} -{"fileVersion": "1.0.0"} -{"Section": "Models"} - -{"Section": "Twins"} - -{"Section": "Relationships"} - -``` - -Rules: - -- `Header` section is required and must be the first section -- `fileVersion` must be `"1.0.0"` -- Models, Twins, Relationships sections are optional but must appear in order -- All objects must be valid JSON on a single line (no embedded newlines) - -## Stream Processing Engine (ImportJob.cs) - -`StreamingImportJob.ExecuteWithCheckpointAsync()` is the core method. - -### Processing Flow - -1. **Header validation** — first call to `ValidateStreamHeaderAsync()` reads first two lines, resets stream -2. **Section dispatch** — line-by-line reading via `PositionTrackingStreamReader` -3. **Batch processing**: - - **Models**: All models are collected in a `List`, then processed in a single `CreateModelsAsync()` call (models may have interdependencies) - - **Twins**: Collected in batches (default 50), each batch sent to `CreateOrReplaceDigitalTwinsInternalAsync()` - - **Relationships**: Collected in batches (default 50), each batch sent to `CreateOrReplaceRelationshipsInternalAsync()` -4. **Connection health monitoring** — `EnsureConnectionHealthyAsync()` checks before processing each line, waits 60s and retries on broken/closed connections -5. **Heartbeat timer** — renews distributed lock every 30s and polls DB for `Cancelling` status - -### Connection Health - -`EnsureConnectionHealthyAsync()` handles: - -- **Closed**: Waits 60s, opens connection. If still not open, throws `DatabaseConnectivityException` -- **Broken**: Closes, waits 60s, reopens. If still broken, throws `DatabaseConnectivityException` -- **Connecting/Executing**: Waits 5s, checks again -- Healthy connections pass through immediately - -On `DatabaseConnectivityException`, the job stays in `Running` status with `FinishedDateTime = null` for automatic resumption. - -### Error Handling - -- Individual item errors are counted but don't stop processing -- Batch failures are logged and counted; the job continues -- `OperationCanceledException` from `combinedCts.Token` → `Cancelled` (DB-initiated cancel) -- `OperationCanceledException` from original token → `Cancelled` (caller-initiated cancel) -- `DatabaseConnectivityException` → return with `Running` status (resumable) -- `ArgumentException` → always re-thrown (validation failure) -- All other exceptions → `DetermineFinalJobStatus()` decides `Succeeded`/`PartiallySucceeded`/`Failed` - -## Checkpointing and Resumption - -### Checkpoint Model - -`ImportJobCheckpoint` tracks: - -- `CurrentSection` — `None`, `Header`, `Models`, `Twins`, `Relationships` -- `LineNumber` — 1-based position in the ND-JSON stream -- `ModelsProcessed`, `TwinsProcessed`, `RelationshipsProcessed`, `ErrorCount` — counters -- `PendingModels` — models collected but not yet batch-processed -- `ModelsCompleted`, `TwinsCompleted`, `RelationshipsCompleted` — section completion flags - -### When Checkpoints Are Saved - -1. **At section boundaries** — when a `{"Section": "..."}` line is encountered -2. **Periodically within sections** — every `CheckpointInterval` items (default: 50) -3. **On DB connectivity loss** — progress is captured before re-throwing (though not saved to DB since connectivity is down) -4. **On final completion** — final checkpoint saved, then cleared on success - -### Resumption Flow - -1. `SeekToLineAsync(targetLineNumber)` resets the stream to beginning, fast-forwards by reading lines until target line -2. Section completion flags (`ModelsCompleted`, `TwinsCompleted`, `RelationshipsCompleted`) allow fully skipping already-processed sections -3. `PendingModels` reconstructs models that were collected but not yet batch-processed - -### PositionTrackingStreamReader - -Wraps a `StreamReader`, tracks 1-based `LineNumber`: - -- `SeekToLineAsync(n)`: `Seek(0, Begin)`, `DiscardBufferedData()`, read lines until line N -- `SkipLinesAsync(n)`: Read and discard N lines from current position -- `Reset()`: Seek to 0, reset counter - -## Distributed Locking (JobService.cs) - -Locks prevent duplicate processing when multiple instances could resume the same job. - -### Lock Columns on `jobs` Table - -| Column | Type | Description | -| --------------------- | -------------- | ------------------------------------------------------ | -| `lock_acquired_at` | `TIMESTAMPTZ` | When lock was acquired | -| `lock_acquired_by` | `VARCHAR(255)` | Instance ID: `{MachineName}-{ProcessId}-{8-char-guid}` | -| `lock_lease_duration` | `INTERVAL` | Default: 5 minutes | -| `lock_heartbeat_at` | `TIMESTAMPTZ` | Last heartbeat timestamp | - -### Lock Operations - -```sql --- Acquire (atomic update only if null or expired): -UPDATE {schema}.jobs SET lock_acquired_at = NOW(), lock_acquired_by = @instanceId, ... -WHERE id = @jobId AND (lock_acquired_at IS NULL OR lock_acquired_at + lock_lease_duration < NOW()) - --- Renew (must own valid lock): -UPDATE {schema}.jobs SET lock_heartbeat_at = NOW() -WHERE id = @jobId AND lock_acquired_by = @instanceId AND lock_acquired_at + lock_lease_duration > NOW() - --- Release: -UPDATE {schema}.jobs SET lock_acquired_at = NULL, lock_acquired_by = NULL, ... -WHERE id = @jobId AND lock_acquired_by = @instanceId -``` - -The heartbeat timer (every 30s) renews the lock and checks for DB-initiated cancellation. - -## API Endpoints - -All under `/jobs/imports`, require `AdminOperations` rate limiting. - -| Method | Route | Description | -| -------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------ | -| `PUT` | `/jobs/imports/{id}` | Create & start import job. Returns `201` immediately (background execution). Body: `{inputBlobUri, outputBlobUri}` | -| `GET` | `/jobs/imports/{id}` | Get job status and results | -| `GET` | `/jobs/imports/` | List all import jobs | -| `POST` | `/jobs/imports/{id}/cancel` | Set status to `Cancelling`. Validates job is `Running` or `Notstarted` | -| `DELETE` | `/jobs/imports/{id}` | Remove job record from DB | -| `POST` | `/jobs/imports/{id}/resume` | Resume from checkpoint. Validates job is `Running` or `Failed` and not locked by another instance | - -## Automatic Resumption (JobResumptionService) - -Registered only when `Parameters:JobsEnabled` is `true`: - -- Waits 10s on startup for app initialization -- Polls every 2 minutes for jobs with `status = 'running'` AND (lock is null OR lock has expired) -- For each import job found: - 1. Validates required blob URIs exist in request data - 2. Acquires distributed lock - 3. Opens input stream (read) and output stream (append mode) - 4. Calls `ResumeImportJobAsync()` with the checkpoint - 5. On failure, marks job as `Failed`, releases lock -- Purges expired jobs once per hour (when `DateTime.UtcNow.Minute == 0`) - -## Database Schema - -Schema: `{graphName}_jobs` (default: `digitaltwins_jobs`) - -```sql -CREATE TABLE {graphName}_jobs.jobs ( - id VARCHAR(255) PRIMARY KEY, - job_type VARCHAR(100) NOT NULL, - status VARCHAR(50) NOT NULL DEFAULT 'notstarted', - created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), - updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), - finished_at TIMESTAMP WITH TIME ZONE NULL, - purge_at TIMESTAMP WITH TIME ZONE NOT NULL, - request_data JSONB NULL, - result_data JSONB NULL, - error_data JSONB NULL, - checkpoint_data JSONB NULL, - lock_acquired_at TIMESTAMP WITH TIME ZONE NULL, - lock_acquired_by VARCHAR(255) NULL, - lock_lease_duration INTERVAL NOT NULL DEFAULT '5 minutes', - lock_heartbeat_at TIMESTAMP WITH TIME ZONE NULL -); -``` - -Created automatically in `JobService` constructor via `InitializeSchemaAsync()`. - -## Configuration - -| Key | Default | Description | -| -------------------------------------- | -------------- | ---------------------------------------------------------- | -| `Parameters:JobsEnabled` | `true` | Enables blob storage services and `JobResumptionService` | -| `Parameters:DefaultBatchSize` | `50` | Items per batch for import/delete jobs | -| `Parameters:DefaultCheckpointInterval` | `50` | Items between checkpoint saves | -| `Parameters:AgeGraphName` | `digitaltwins` | Graph name (used for schema isolation: `{graphName}_jobs`) | - -`ImportJobOptions`: - -- `ContinueOnFailure` (default: `true`) -- `BatchSize` (default: `50`) -- `CheckpointInterval` (default: `50`) -- `OperationTimeout` (default: 30 min) -- `HeartbeatInterval` (default: 30s) -- `LeaveOpen` (default: `false`) - -## SDK Usage - -```csharp -// Synchronous import from streams -var result = await client.ImportGraphAsync( - "my-job-id", - inputStream, - outputStream, - options: new ImportJobOptions { BatchSize = 100 }, - cancellationToken -); - -// Background import via REST API (handled by ImportJobEndpoints) -// PUT /jobs/imports/{id} with body { "inputBlobUri": "...", "outputBlobUri": "..." } - -// Resume from checkpoint -var result = await client.ResumeImportJobAsync( - "my-job-id", - inputStream, - outputStream, - cancellationToken -); -``` diff --git a/content/docs/graph/how-to-guides/import-jobs.mdx b/content/docs/graph/how-to-guides/import-jobs.mdx index 672aa75..af98d37 100644 --- a/content/docs/graph/how-to-guides/import-jobs.mdx +++ b/content/docs/graph/how-to-guides/import-jobs.mdx @@ -1,156 +1,164 @@ --- -title: "Import Jobs" +title: Import Jobs icon: Upload -description: "How to use import jobs for bulk data ingestion with SAS tokens and cloud storage." +description: Bulk-ingest models, twins and relationships from cloud storage with resumable background jobs. --- -Import jobs allow you to bulk ingest data into Konnektr Graph using cloud storage blobs. This guide explains how import jobs work, how to use SAS tokens for Azure Blob Storage, and outlines future support for AWS S3 and Google Cloud Storage. +Import jobs bulk-ingest graph data from a blob in cloud storage. The job runs in the +background, reports progress, and resumes from a checkpoint if the API restarts — so a +million-line import does not depend on a single HTTP request staying open. -## Overview +This page covers what you need to *use* jobs. The configuration keys live in the +[configuration reference](../reference/configuration). -An import job is a background process that reads data from an input blob (e.g., NDJSON, CSV) and writes results to an output blob. This is useful for bulk loading twins, relationships, or telemetry data. +## When to use an import job -## Supported Storage Providers +- Loading an existing dataset (an ADT export, a dump, a generated ontology). +- Anything larger than a single batch request: `POST /digitaltwins` and `POST /relationships` + are capped by `Parameters:MaxBatchSize` (default 2000) and reject larger payloads with 400. +- Work that must survive a pod restart — the job, not your shell, owns the progress. -- **Azure Blob Storage (SAS tokens)**: Supported — pass a blob URI that carries the SAS token. -- **Managed Identity (Azure)**: Supported when the API pod runs with an Azure workload identity. -- **AWS S3**: Supported via S3 URIs and default AWS credentials or pre-signed URLs. -- **Google Cloud Storage**: Supported via GCS URIs and default GCP credentials or signed URLs. +## Supported storage -## Using Azure Blob Storage (SAS Tokens) +| Provider | URI form | Credentials | +|---|---|---| +| Azure Blob Storage | `https://.blob.core.windows.net//?sv=…&sig=…` | SAS token in the query string, or managed identity | +| AWS S3 | `s3://bucket/key` or `https://bucket.s3.amazonaws.com/key` | Default AWS credential chain, or a pre-signed URL | +| Google Cloud Storage | `gs://bucket/key` or `https://storage.googleapis.com/bucket/key` | Default GCP credentials, or a signed URL | -SAS tokens let import jobs read and write Azure Blob Storage without any Azure credential on the service. SAS tokens grant temporary, scoped access to blobs. +Input needs **read**; output needs **write**. For Azure SAS that means `sp=r` and `sp=w`; for +S3/GCS it means your IAM/service-account policy allows the calls. -**Example Blob URI:** -``` -https://.blob.core.windows.net//?sv=...&sig=... -``` - -- The SAS token must be included in the URI query string. -- Both input and output blob URIs must be accessible with the provided SAS token. -- The SAS token must grant **read** permission for input blobs and **write** permission for output blobs (use `sp=r` and/or `sp=w` in the SAS token). -- When the URI carries a SAS token, no Azure credentials or managed identity are needed. - -## Using AWS S3 - -Import jobs support AWS S3 URIs. You can use either the S3 URI format or HTTPS format: - -**Example S3 URIs:** -``` -s3://my-bucket/my-object.ndjson -https://my-bucket.s3.amazonaws.com/my-object.ndjson -``` - -- The application uses default AWS credentials (IAM role, environment variables, or AWS config). -- You may also use pre-signed URLs for temporary access. -- The credentials or signed URL must grant **read** permission for input blobs and **write** permission for output blobs. -- For append/resume, the service downloads the existing object, appends new data, and re-uploads. +When the URI carries a SAS token or a pre-signed URL, the service needs no cloud credential at +all. -## Using Google Cloud Storage +## Starting a job -Import jobs support Google Cloud Storage URIs. You can use either the GCS URI format or HTTPS format: - -**Example GCS URIs:** -``` -gs://my-bucket/my-object.ndjson -https://storage.googleapis.com/my-bucket/my-object.ndjson +```bash +curl -X PUT http://localhost:8080/jobs/imports/import-2026-10-20 \ + -H 'Content-Type: application/json' \ + -d '{ + "inputBlobUri": "https://acct.blob.core.windows.net/data/export.ndjson?sv=...&sp=r&sig=...", + "outputBlobUri": "https://acct.blob.core.windows.net/data/export.result.ndjson?sv=...&sp=w&sig=..." + }' ``` -- The application uses default GCP credentials (service account, environment variables, or GCP config). -- You may also use signed URLs for temporary access. -- The credentials or signed URL must grant **read** permission for input blobs and **write** permission for output blobs. -- For append/resume, the service downloads the existing object, appends new data, and re-uploads. - -## How Import Jobs Work - -1. **Create an import job** via the API, providing: - - `inputBlobUri`: The source blob URI (with SAS token, AWS credentials, or GCP credentials/signed URL). - - `outputBlobUri`: The destination blob URI (with SAS token, AWS credentials, or GCP credentials/signed URL). - - Additional job parameters as needed. -2. The job runs in the background, reading from the input blob and writing results to the output blob. -3. You can monitor job status, cancel, or resume jobs via the API. For S3 and GCS, resuming a job will append to the existing output object. - -## Required Permissions +The call returns `201` immediately; execution is in the background. The job id is yours — reuse +it and you overwrite that job's record rather than creating a second one. +| Method | Route | Purpose | +|---|---|---| +| `PUT` | `/jobs/imports/{id}` | Create and start (body: `inputBlobUri`, `outputBlobUri`) | +| `GET` | `/jobs/imports/{id}` | Status, counters and errors | +| `GET` | `/jobs/imports` | List jobs | +| `POST` | `/jobs/imports/{id}/cancel` | Request cancellation (valid while `Notstarted`/`Running`) | +| `POST` | `/jobs/imports/{id}/resume` | Resume from the last checkpoint (valid while `Running`/`Failed`, and not locked elsewhere) | +| `DELETE` | `/jobs/imports/{id}` | Delete the job record | -For all providers, you must ensure that: +## The input format -- **Input blob**: The credentials, SAS token, or signed URL must grant **read** access. -- **Output blob**: The credentials, SAS token, or signed URL must grant **write** access. -- For Azure SAS tokens, use the `sp=r` (read) and/or `sp=w` (write) permissions. -- For AWS and GCS, ensure your IAM/service account policies allow the required operations. +NDJSON only — one JSON object per line, no embedded newlines, sections in a fixed order: -## NDJSON Format Requirements - -Import jobs require NDJSON files with a specific structure. Each section must be a line-delimited JSON object, in the following order: - -``` +```jsonl {"Section": "Header"} -{"fileVersion": "1.0.0", "author": "your-name", "organization": "your-org"} +{"fileVersion": "1.0.0"} {"Section": "Models"} {"Section": "Twins"} - + {"Section": "Relationships"} - + ``` -**Formatting Guidelines:** -- All objects must be valid JSON and single-line (no embedded newlines). -- The header section is required and should include metadata. -- Models, twins, and relationships sections are optional but must follow the order above. -- See the [Migration Guide](./migration-guide) for more details and code samples. +Rules the validator actually enforces: + +- The `Header` section is **required** and must be first. +- `fileVersion` must be exactly `"1.0.0"`. +- `Models`, `Twins` and `Relationships` are optional, but appear in that order. +- Every object must be valid JSON on a single line. -### Example NDJSON Generator (.NET) +Models are processed as one unit (they can reference each other through inheritance), while +twins and relationships are batched. + +JSON-LD and other formats are not supported. + +### Generating the file ```python title="ndjson_generator.py" import json -def write_ndjson(models, twins, relationships, file_path, header=None): - with open(file_path, 'w', encoding='utf-8') as f: - # Header section - f.write(json.dumps({"Section": "Header"}) + '\n') - if header is None: - header_obj = {"fileVersion": "1.0.0", "author": "authorName", "organization": "organization"} - else: - header_obj = header - f.write(json.dumps(header_obj) + '\n') - - # Models section - f.write(json.dumps({"Section": "Models"}) + '\n') - for model in models: - # model should be a dict or already serialized string - if isinstance(model, str): - f.write(model.strip().replace('\n', '') + '\n') - else: - f.write(json.dumps(model) + '\n') - - # Twins section - f.write(json.dumps({"Section": "Twins"}) + '\n') - for twin in twins: - f.write(json.dumps(twin) + '\n') - - # Relationships section - f.write(json.dumps({"Section": "Relationships"}) + '\n') - for rel in relationships: - f.write(json.dumps(rel) + '\n') +def write_ndjson(models, twins, relationships, path, header=None): + header_obj = header or { + "fileVersion": "1.0.0", + "author": "authorName", + "organization": "organization", + } + with open(path, "w", encoding="utf-8") as f: + # Header is mandatory and must come first + f.write(json.dumps({"Section": "Header"}) + "\n") + f.write(json.dumps(header_obj) + "\n") + + f.write(json.dumps({"Section": "Models"}) + "\n") + for model in models: + # models are often handed over as already-serialized JSON + line = model.strip().replace("\n", "") if isinstance(model, str) else json.dumps(model) + f.write(line + "\n") + + f.write(json.dumps({"Section": "Twins"}) + "\n") + for twin in twins: + f.write(json.dumps(twin) + "\n") + + f.write(json.dumps({"Section": "Relationships"}) + "\n") + for rel in relationships: + f.write(json.dumps(rel) + "\n") ``` -This function writes the NDJSON file in the required format. Pass lists of models, twins, and relationships as Python dicts or JSON strings. Each object is written on a single line. -**Note:** Only NDJSON format is supported for import jobs. Do not use JSON-LD or other formats. +## Statuses ---- +| Status | Meaning | +|---|---| +| `Notstarted` | Created, not picked up yet | +| `Running` | Reading the input stream | +| `Succeeded` | Everything imported | +| `PartiallySucceeded` | Finished, with items that failed — see the errors | +| `Failed` | Nothing imported, or the job gave up | +| `Cancelling` | Cancellation requested; the worker has not stopped yet | +| `Cancelled` | Stopped | -## Future Support +Two behaviours worth designing around: -- Additional cloud providers and custom storage endpoints may be supported in future releases. +- **Cancellation is cooperative.** `cancel` sets `Cancelling`; the worker checks it on a + heartbeat, so expect a short delay before `Cancelled`. +- **A lost database connection does not fail the job.** It stays `Running` with no finish time + and is picked up again later — from its last checkpoint. -## Notes +## Resumption -- You may use managed identity for Azure Blob Storage if your environment supports it. -- All blob URIs must be valid and accessible from the Konnektr Graph instance. -- See the [API Reference](../reference/api) for endpoint details and request formats. +Progress is checkpointed at section boundaries and every `Parameters:DefaultCheckpointInterval` +items (default 50). On resume, the job seeks back to the recorded line and continues; sections +that already completed are skipped outright. ---- +An interrupted job is recovered automatically: the service polls for `Running` jobs whose lock +is free or expired (every two minutes) and resumes them. You only need `resume` when you want +to drive that decision yourself — for example after fixing a bad input line, where the job is +`Failed`. + +For S3 and GCS, resuming appends to the existing output object rather than replacing it. + +## Permissions + +| Blob | Needs | +|---|---| +| Input | read | +| Output | write | + +Azure: `sp=r` for input, `sp=w` for output. AWS/GCP: the corresponding IAM or service-account +permissions. All URIs must be reachable from the Konnektr Graph instance — a URI that works on +your laptop but not inside the cluster is the most common cause of an immediately failed job. + +## See also -For questions or troubleshooting, see [How-To Guides](./) or reach out via GitHub Discussions. +- [API reference](../reference/api/import-jobs/ListImportJobs) — one page per endpoint +- [Configuration reference](../reference/configuration) — `JobsEnabled`, `DefaultBatchSize`, + `DefaultCheckpointInterval` +- [Migration guide](./migration-guide) — exporting from Azure Digital Twins into this format