SKEG · GUIDES

Batch ingestion

Bound batches, inspect per-item outcomes and repair an incomplete import.

Skeg 0.8 · Development documentation

Use SKEG.VMSET to send several vector rows in one request. Skeg applies each row independently and returns an outcome for each one. In this exercise, you will send three rows, correct the rejected row and read all three back.

Start a local server

Install Skeg 0.8, use a writable temporary directory and make sure port 6382 is free. In one terminal, start a local server for the example:

data_dir=$(mktemp -d) &&
  skeg --protocol resp3 --data-dir "$data_dir" --addr 127.0.0.1:6382

Use a second terminal with an active Python virtual environment. Install the redis client with python -m pip install 'redis>=5'. The example uses RESP2 replies on this listener and keeps vectors as bytes.

Prepare the rows

Give every source record a stable numeric ID. Each item contains an ID, encoded vector and payload field:

SKEG.VMSET <index> <id> <vector> <payload> [<id> <vector> <payload> ...]

Encode coordinates as little-endian float32 bytes. The payload position is required. An empty field leaves a new row without a payload and preserves the current payload on an existing row. Supply the complete payload when you want to replace it. To clear its contents, send SKEG.VSET with PAYLOAD and an empty bulk string.

Use each ID at most once in a batch. Work runs concurrently; response order does not establish execution order for two replacements of the same ID.

Bound request size

The handler applies these ceilings before sending items to shards:

LimitValue
Items in one batch4096
Sum of encoded vector bytes64 MiB
One item’s payload1 MiB

These are ceilings, not target batch sizes or a complete memory allowance. RESP framing, payload totals, connection buffering and memory admission can reject a request below them. Start with small batches and bound concurrent requests as well as item count. Split oversized source streams into batches without materializing the whole dataset in memory.

Understand the two levels of failure

Malformed triples, an invalid numeric ID, vector bytes not divisible by four, or a handler size-limit violation produce a command-level error before item dispatch. Correct the request before sending it again.

Once dispatched, item checks such as dimension validation, finite coordinates and quotas can fail independently. The response is an array with one result per input item, in input order. A result is RESP OK or that item’s error. Other items can succeed even when one fails.

For example, an array shaped like [OK, error, OK] means the first and third items succeeded. Do not resubmit all three while treating the array as one failed transaction. A connection failure before a complete response is a different situation: some or all item outcomes may be unknown.

Work through a partial failure

Save the following as batch_ingestion.py, or download the complete script. It creates its own four-dimensional disk index, sends three rows and deliberately gives the middle row the wrong dimension. It prints every outcome, then writes a corrected middle row separately.

import struct

import redis
from redis.backoff import NoBackoff
from redis.retry import Retry


def vector(values):
    return struct.pack("<" + "f" * len(values), *values)


with redis.Redis(
    host="127.0.0.1", port=6382, protocol=2, decode_responses=False,
    socket_connect_timeout=5, socket_timeout=30, retry=Retry(NoBackoff(), 0),
) as client:
    index = "batch_ingestion_demo"
    client.execute_command(
        "SKEG.VINDEX.CREATE", index, 4,
        "KIND", "tq2", "BACKEND", "disk", "PERSISTENCE", "durable",
    )
    rows = [
        (1, [1.0, 0.0, 0.0, 0.0], b"topic=account revision=1"),
        (2, [0.0, 1.0], b"topic=billing revision=1"),
        (3, [0.8, 0.6, 0.0, 0.0], b"topic=account revision=1"),
    ]
    command = ["SKEG.VMSET", index]
    for row_id, coordinates, payload in rows:
        command.extend((row_id, vector(coordinates), payload))

    outcomes = client.execute_command(*command)
    if not isinstance(outcomes, list) or len(outcomes) != len(rows):
        raise RuntimeError("Incomplete or unexpected batch response")

    failed = []
    for (row_id, _, _), outcome in zip(rows, outcomes):
        if outcome == b"OK":
            print(row_id, "stored")
        elif isinstance(outcome, redis.exceptions.ResponseError):
            failed.append(row_id)
            print(row_id, "error:", outcome)
        else:
            raise RuntimeError(f"Unexpected outcome for row {row_id}: {outcome!r}")

    if failed != [2]:
        raise RuntimeError("Unexpected failures; inspect them before repairing")

    if client.execute_command("SKEG.VGET", index, 2) is not None:
        raise RuntimeError("The rejected row should be absent")

    corrected = vector([0.0, 1.0, 0.0, 0.0])
    client.execute_command(
        "SKEG.VSET", index, 2, corrected, "PAYLOAD", b"topic=billing revision=1",
    )
    expected = {1: vector(rows[0][1]), 2: corrected, 3: vector(rows[2][1])}
    for row_id, expected_vector in expected.items():
        raw = client.execute_command("SKEG.VGET", index, row_id)
        if raw != expected_vector:
            raise RuntimeError(f"Unexpected vector for row {row_id}")
        print(row_id, struct.unpack("<4f", raw))

Run it with python batch_ingestion.py. The first and third outcomes should report stored and the second should describe a dimension mismatch. The script checks that row 2 is absent before writing the correction. It then compares the stored vector bytes for all three rows.

The script disables automatic transport retries and stops on a command-level exception or an unexpected response. It repairs only the deliberate dimension error in row 2. The script leaves the index available for inspection. Remove the example index before running it again.

In redis-py, item errors can be exception objects inside the returned list. Check the list elements even when execute_command itself did not raise. Other clients may expose a different batch-result type; check that they consume the full response and preserve all item outcomes.

Resume a larger import

Keep a source-side import record containing the index identity, source position, IDs and outcomes. Advance a checkpoint only after the expected replies have been received and failures have been recorded for repair. Track acknowledged, rejected and unresolved items separately. If the connection drops before the client reads the whole reply, reconcile unresolved rows by ID using the write-outcome procedure.

Retry an explicitly rejected item only after classifying its error. Correct dimensions or payloads, resolve quotas, or use bounded backoff for a retryable admission refusal. For timeouts and disconnects, follow write outcomes before resending.

Serialize updates for the same ID or otherwise coordinate writers. Stable IDs prevent duplicate row identities, but replaying an old replacement can still overwrite newer content.

Consolidate and clean up

An explicit consolidation is optional after loading:

redis-cli -h 127.0.0.1 -p 6382 -3 SKEG.VINDEX.CONSOLIDATE batch_ingestion_demo

Handle its outcome separately from ingestion. A failed consolidation does not undo the stored rows. Read index management for maintenance and effective index settings.

When finished inspecting the example, remove its index:

redis-cli -h 127.0.0.1 -p 6382 -3 SKEG.VINDEX.DROP batch_ingestion_demo

Stop the example server with Ctrl+C. For an application import, maintain any separately stored documents alongside the vector rows and payloads.