CodeSampleX

Ejemplo

flatbuffers 25.12.19: serialize and deserialize data using flatbuffers.Builder

Muestra verificada para pypi flatbuffers 25.12.19: serialize and deserialize data using flatbuffers.Builder. El contrato se ejecutó en python 3.12 · linux…

sha256:c857c6fce22159b271ccb77bceb842640241232ef609e20d92675087533a9b20

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python uv

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-25

Caso

HOW
Objetivo
serialize and deserialize data using flatbuffers.Builder
Paquetes
Símbolos
  • flatbuffers.Builder
Entorno
python 3.12
Creado
2026-08-25T20:11:39Z

Contrato

  1. flatbuffers.Builder initializes with specified buffer capacity and tracks buffer offsets
  2. flatbuffers.Builder.CreateString serializes null-terminated UTF-8 strings into the buffer and returns valid offset
  3. flatbuffers.Builder.CreateByteVector serializes raw byte arrays and returns vector offset
  4. flatbuffers.Builder.CreateSharedString deduplicates repeated strings by reusing previously serialized offsets
  5. flatbuffers.Builder table serialization with StartObject, PrependInt32Slot, PrependFloat64Slot, and EndObject encodes vtables correctly
  6. flatbuffers.Builder.Finish sets the root table offset at index 0 allowing Table deserialization
  7. flatbuffers.Builder.FinishSizePrefixed prefixes the output buffer with the total buffer payload size
  8. flatbuffers.Builder.Clear resets buffer offsets allowing the builder instance to be reused
  9. flatbuffers.Builder enforces nesting rules by raising IsNestedError on nested StartObject calls
  10. flatbuffers.Builder raises BuilderNotFinishedError when Output is called before Finish
  11. flatbuffers.Builder raises IsNotNestedError when EndObject is called without an active StartObject

Archivos

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • spec.json
  • test/contract.py
  • uv.lock

Descargar el artefacto de código fuente (tar.gz)

Código fuente

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: serialize and deserialize data using flatbuffers.Builder
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/flatbuffers@25.12.19
Demonstrate these symbols/APIs:
  - flatbuffers.Builder
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:69150a0b4d7d8fc2f1281963a869a511549a13d38715c006a126d9c5d3c30c22","contract":["flatbuffers.Builder initializes with specified buffer capacity and tracks buffer offsets","flatbuffers.Builder.CreateString serializes null-terminated UTF-8 strings into the buffer and returns valid offset","flatbuffers.Builder.CreateByteVector serializes raw byte arrays and returns vector offset","flatbuffers.Builder.CreateSharedString deduplicates repeated strings by reusing previously serialized offsets","flatbuffers.Builder table serialization with StartObject, PrependInt32Slot, PrependFloat64Slot, and EndObject encodes vtables correctly","flatbuffers.Builder.Finish sets the root table offset at index 0 allowing Table deserialization","flatbuffers.Builder.FinishSizePrefixed prefixes the output buffer with the total buffer payload size","flatbuffers.Builder.Clear resets buffer offsets allowing the builder instance to be reused","flatbuffers.Builder enforces nesting rules by raising IsNestedError on nested StartObject calls","flatbuffers.Builder raises BuilderNotFinishedError when Output is called before Finish","flatbuffers.Builder raises IsNotNestedError when EndObject is called without an active StartObject"],"goal":"serialize and deserialize data using flatbuffers.Builder","kind":"HOW","packages":["pkg:pypi/flatbuffers@25.12.19"],"schemaVersion":1,"symbols":["flatbuffers.Builder"]},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"uv","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/flatbuffers@25.12.19"],"schemaVersion":1,"subject":"pkg:pypi/flatbuffers@25.12.19","symbols":["flatbuffers.Builder"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "sample-flatbuffers"
version = "0.1.0"
requires-python = ">=3.8"
dependencies = [
    "flatbuffers==25.12.19",
]
requirements.txt
flatbuffers==25.12.19
spec.json
{
  "schemaVersion": 1,
  "goal": "serialize and deserialize data using flatbuffers.Builder",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/flatbuffers@25.12.19"
  ],
  "symbols": [
    "flatbuffers.Builder"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.py
import flatbuffers
from flatbuffers import Builder, encode, number_types
from flatbuffers.builder import IsNestedError, IsNotNestedError, BuilderNotFinishedError
from flatbuffers.table import Table


def test_builder_initialization():
    b = Builder(256)
    assert b.Offset() == 0, f"Expected initial offset 0, got {b.Offset()}"
    assert len(b.Bytes) == 256, f"Expected initial buffer size 256, got {len(b.Bytes)}"


def test_create_string():
    b = Builder(256)
    s_offset = b.CreateString("sample_value")
    assert s_offset > 0, f"Expected positive string offset, got {s_offset}"
    b.StartObject(1)
    b.PrependUOffsetTRelativeSlot(0, s_offset, 0)
    root = b.EndObject()
    b.Finish(root)

    buf = b.Output()
    root_pos = encode.Get(number_types.UOffsetTFlags.packer_type, buf, 0)
    tab = Table(buf, root_pos)
    field_offset = tab.Offset(4)
    assert field_offset != 0, "String field offset not found in vtable"
    decoded_str = tab.String(tab.Pos + field_offset)
    assert decoded_str == b"sample_value", f"Decoded string mismatch: {repr(decoded_str)}"


def test_create_byte_vector():
    b = Builder(256)
    raw_payload = b"\xde\xad\xbe\xef\x01\x02\x03\x04"
    v_offset = b.CreateByteVector(raw_payload)
    assert v_offset > 0, f"Expected positive byte vector offset, got {v_offset}"

    b.StartObject(1)
    b.PrependUOffsetTRelativeSlot(0, v_offset, 0)
    root = b.EndObject()
    b.Finish(root)

    buf = b.Output()
    root_pos = encode.Get(number_types.UOffsetTFlags.packer_type, buf, 0)
    tab = Table(buf, root_pos)
    field_offset = tab.Offset(4)
    assert field_offset != 0, "Byte vector field offset not found in vtable"
    vec_len = tab.VectorLen(field_offset)
    assert vec_len == len(raw_payload), f"Vector length mismatch: {vec_len} != {len(raw_payload)}"
    vec_start = tab.Vector(field_offset)
    assert bytes(tab.Bytes[vec_start:vec_start + vec_len]) == raw_payload, "Vector payload mismatch"


def test_shared_string_deduplication():
    b = Builder(256)
    s1 = b.CreateSharedString("reused_identifier")
    s2 = b.CreateSharedString("reused_identifier")
    assert s1 == s2, f"CreateSharedString did not deduplicate: {s1} != {s2}"


def test_table_serialization_and_deserialization():
    b = Builder(512)
    name_offset = b.CreateString("item_name")

    b.StartObject(3)
    b.PrependInt32Slot(0, 123456, 0)
    b.PrependFloat64Slot(1, 3.1415926535, 0.0)
    b.PrependUOffsetTRelativeSlot(2, name_offset, 0)
    root = b.EndObject()
    b.Finish(root)

    buf = b.Output()
    root_pos = encode.Get(number_types.UOffsetTFlags.packer_type, buf, 0)
    tab = Table(buf, root_pos)

    # Slot 0 (vtable index 4)
    off0 = tab.Offset(4)
    assert off0 != 0, "Field 0 offset missing"
    val0 = tab.Get(number_types.Int32Flags, tab.Pos + off0)
    assert val0 == 123456, f"Field 0 mismatch: {val0} != 123456"

    # Slot 1 (vtable index 6)
    off1 = tab.Offset(6)
    assert off1 != 0, "Field 1 offset missing"
    val1 = tab.Get(number_types.Float64Flags, tab.Pos + off1)
    assert abs(val1 - 3.1415926535) < 1e-7, f"Field 1 mismatch: {val1}"

    # Slot 2 (vtable index 8)
    off2 = tab.Offset(8)
    assert off2 != 0, "Field 2 offset missing"
    val2 = tab.String(tab.Pos + off2)
    assert val2 == b"item_name", f"Field 2 mismatch: {repr(val2)}"


def test_finish_size_prefixed():
    b = Builder(256)
    b.StartObject(1)
    b.PrependInt32Slot(0, 777, 0)
    root = b.EndObject()
    b.FinishSizePrefixed(root)

    buf = b.Output()
    prefix_size = encode.Get(number_types.Uint32Flags.packer_type, buf, 0)
    assert prefix_size == len(buf) - 4, f"Size prefix mismatch: {prefix_size} != {len(buf) - 4}"


def test_clear_and_reuse():
    b = Builder(256)
    b.CreateString("temp_string")
    assert b.Offset() > 0, "Offset should be positive after CreateString"
    b.Clear()
    assert b.Offset() == 0, f"Expected offset 0 after Clear(), got {b.Offset()}"


def test_nesting_and_lifecycle_exceptions():
    # Calling Output before Finish raises BuilderNotFinishedError
    b1 = Builder(256)
    try:
        b1.Output()
        assert False, "Output before Finish did not raise BuilderNotFinishedError"
    except BuilderNotFinishedError:
        pass

    # Nested StartObject raises IsNestedError
    b2 = Builder(256)
    b2.StartObject(1)
    try:
        b2.StartObject(1)
        assert False, "Nested StartObject did not raise IsNestedError"
    except IsNestedError:
        pass

    # EndObject without StartObject raises IsNotNestedError
    b3 = Builder(256)
    try:
        b3.EndObject()
        assert False, "EndObject without StartObject did not raise IsNotNestedError"
    except IsNotNestedError:
        pass


def main():
    test_builder_initialization()
    test_create_string()
    test_create_byte_vector()
    test_shared_string_deduplication()
    test_table_serialization_and_deserialization()
    test_finish_size_prefixed()
    test_clear_and_reuse()
    test_nesting_and_lifecycle_exceptions()
    print("All flatbuffers contract assertions passed.")


if __name__ == "__main__":
    main()
uv.lock
version = 1
revision = 3
requires-python = ">=3.8"

[[package]]
name = "flatbuffers"
version = "25.12.19"
source = { registry = "https://pypi.org/simple" }
wheels = [
    { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" },
]

[[package]]
name = "sample-flatbuffers"
version = "0.1.0"
source = { virtual = "." }
dependencies = [
    { name = "flatbuffers" },
]

[package.metadata]
requires-dist = [{ name = "flatbuffers", specifier = "==25.12.19" }]

Seeder de origen

anónimo