Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ and the OpenVINO runtime baseline evolve independently:

## Unreleased

## 0.2.1

Patch release with correctness and memory safety fixes.

### Nim API

- Reject tensor copies involving types that contain Nim-managed references.
Raw byte copies of these values can corrupt ownership and memory.
- Reject negative shape dimensions even when another dimension is zero.
- Reject embedded NUL characters in C-bound names, properties, device names
and paths instead of silently truncating them.
- Avoid a deadline overflow when a completion queue has a long timeout.

## 0.2.0

Released on 2026-10-18 as
Expand Down
29 changes: 29 additions & 0 deletions DEVLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ Phase numbers refer to

## English

### 2026-11-15 0.2.1 correctness fixes

Validate all static dimensions before applying the zero-size shortcut; reject
embedded NULs at C string boundaries; and measure completion queue timeouts
using elapsed monotonic time rather than constructing an overflowing deadline.
Regression tests cover each reproduced failure, including a long timeout and
valid zero-sized shapes whose other dimensions would otherwise overflow.

### 2026-11-15 Tensor copy ownership safety

The typed tensor copy functions checked element widths but also accepted Nim
types containing managed references. Copying raw tensor bytes over such a
value can corrupt reference ownership. They now reject types for which Nim's
`supportsCopyMem` is false, before accessing the tensor or runtime. A
runtime-free regression covers all four entry points and a nested string.

### 2026-09-24 Phase 0: audit the prototype and freeze the scope

Audited the Resonance prototype that this package replaces, and verified the
Expand Down Expand Up @@ -686,6 +702,19 @@ ThreadSanitizer cannot run because OpenVINO loads `libtbbbind` with

## 中文

### 2026-11-15 0.2.1 正确性修复

先校验全部静态维度再处理零元素形状;拒绝 C 字符串边界中的 NUL;完成队列用单调时间
的已耗时计算超时,避免构造溢出的截止时间。回归测试覆盖每个复现的问题,包括超长超时
和其他维度乘积会溢出的合法零元素形状。

### 2026-11-15 张量复制的引用安全

张量类型化复制原先只检查元素宽度,也会接受包含 Nim 托管引用的类型。将张量字节直接
覆盖这些值可能破坏引用的所有权。现在四个入口在访问张量或运行时之前,拒绝 Nim 的
`supportsCopyMem` 判定不能按字节复制的类型;无需运行时的回归测试覆盖了四个入口和
嵌套字符串。

### 2026-09-24 Phase 0:审计原型并冻结范围

审计了本包要取代的 Resonance 原型,并且没有采信计划里的 ABI 论断,而是逐项
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ Corporation.** OpenVINO is a trademark of Intel Corporation.

## Status

Version `0.2.1` contains correctness and memory safety fixes; see the
[release notes](RELEASE_NOTES.md).

Version `0.2.0` was released on 2026-10-18 and adds asynchronous inference,
dynamic and partial shapes with reshape, and declarative layout and
preprocessing. Download the source archives from the
Expand Down
2 changes: 2 additions & 0 deletions README_zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Corporation 的认可或附属关系。** OpenVINO 是 Intel Corporation 的商

## 项目状态

版本 `0.2.1` 包含正确性和内存安全修复,详见[发布说明](RELEASE_NOTES.md)。

版本 `0.2.0` 已于 2026-10-18 发布([GitHub Release](https://github.com/AbyssGG/OpenVINO-Nim-API/releases/tag/v0.2.0)),新增异步推理(`startAsync`、`wait`、
`waitFor`、`cancel` 与 `CompletionQueue`,不在 OpenVINO 线程上运行任何 Nim 代码,
因此不提供用户回调)、动态与部分形状(`PartialShape`、`Port.partialShape`、
Expand Down
75 changes: 14 additions & 61 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
@@ -1,68 +1,21 @@
# OpenVINO Nim API 0.2.0
# OpenVINO Nim API 0.2.1

OpenVINO Nim API 0.2.0 adds asynchronous inference, dynamic shapes and
declarative preprocessing to the community-maintained Nim bindings for the
OpenVINO Runtime C API. It is not an official Intel or OpenVINO project.
This patch release fixes correctness and memory safety issues in the
community-maintained Nim bindings for the OpenVINO Runtime C API.

Published as [`v0.2.0`](https://github.com/AbyssGG/OpenVINO-Nim-API/releases/tag/v0.2.0)
on 2026-10-18.
## Fixes

## Highlights

- **Asynchronous inference.** `startAsync`, `wait`, `waitFor` and `cancel` on
`InferRequest`, with `OpenVinoBusyError` and `OpenVinoCancelledError`.
`CompletionQueue` tells one Nim thread which of many requests has finished.
No Nim code runs on OpenVINO's threads: the package installs one internal C
callback that only records the completion, so user callbacks are
deliberately not offered. Closing a running request is safe.
- **Dynamic shapes.** `PartialShape` and `Dimension` describe dynamic, bounded
and lower-bounded dimensions; `Port.partialShape` reads them; `Model.reshape`
changes them by input, index, name or several names atomically. One compiled
dynamic model infers different batch sizes.
- **Layout and preprocessing.** A `PreprocessPlan` describes element type,
layout, color format, spatial size, resize, mean, scale, crop, pad and
channel reversal as a plain Nim value, and `applyPreprocessing` builds the
prepared model in one call that never lets an OpenVINO child object escape.
- **Measured, not assumed.** Ten upstream behaviours were measured before the
design was fixed, and two corrected the plan. All are pinned by smoke tests
and recorded in ADRs 0003 to 0005.
- Reject tensor byte copies of Nim types containing managed references.
- Validate every shape dimension even when a zero dimension is present.
- Reject embedded NUL characters in C-bound names, properties, devices and
file paths rather than silently truncating them.
- Avoid overflowing a completion queue's deadline for very long timeouts.

## Compatibility

Targets OpenVINO `2026.4.1` (and supports `2026.4.0`) and requires Nim `2.0.0`
or newer; `0.1.x` code compiles and behaves as before. Verified on Windows 11
x86_64 (CPU, Intel iGPU, NVIDIA dGPU, Intel NPU) and Ubuntu 26.04 x86_64 (CPU,
valgrind). The Intel NPU plugin needs bounded or static shapes and does not
support `cancel`. See [the compatibility matrix](docs/compatibility.md).

## Installation

Install OpenVINO Runtime `2026.4.x` separately and configure its library search
path, then install the Nim package:

```shell
nimble refresh
nimble install openvino
```

## Release assets

The published `v0.2.0` assets are the four canonical, checksummed files the
release workflow builds from the tagged commit:

- `openvino-nim-0-2-0-2026-10-18-ov2026-4-1.zip`
- `openvino-nim-0-2-0-2026-10-18-ov2026-4-1.tar.gz`
- `openvino-nim-0-2-0-2026-10-18-ov2026-4-1.zip.sha256`
- `openvino-nim-0-2-0-2026-10-18-ov2026-4-1.tar.gz.sha256`

Each archive has one top-level directory named after the base name and contains
no OpenVINO runtime, model weights or credentials. Verify a download with the
sidecar from the same Release:

```shell
sha256sum -c openvino-nim-0-2-0-2026-10-18-ov2026-4-1.zip.sha256
sha256sum -c openvino-nim-0-2-0-2026-10-18-ov2026-4-1.tar.gz.sha256
```
The package targets OpenVINO `2026.4.1` and requires Nim `2.0.0` or newer.
The changes reject inputs that could previously cause incorrect behaviour.
The 0.2.1 changes have not been tested on GPU or NPU hardware.
See [the compatibility matrix](docs/compatibility.md) for previous releases.

For the complete change list, see [CHANGELOG.md](CHANGELOG.md). For problems,
see [the troubleshooting guide](docs/troubleshooting.md).
For the complete change list, see [CHANGELOG.md](CHANGELOG.md).
5 changes: 3 additions & 2 deletions docs/api-overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ completed. Tensors created by OpenVINO, including by `tensorFrom`, may be
closed once bound: the request keeps its own reference. Tensor getters return
new handles that you must close, even when their storage belongs to the
request. `tensorFrom` copies input data; `toSeq` returns an independent Nim
sequence. Typed access checks element width and size, but does not convert
data or distinguish integer and floating-point types of the same width.
sequence. Typed access rejects types containing Nim-managed references and
checks element width and size, but does not convert data or distinguish
integer and floating-point types of the same width.
Match the Nim data type to the model's declared element type.

For repeated inference, keep the compiled model and request, update input
Expand Down
2 changes: 1 addition & 1 deletion openvino.nimble
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ proc stringMetadata(name: string): string =
#
# `nimble releaseCheck` closes the loop by asserting each literal against
# src/openvino/version.nim, so the single source of truth still wins.
version = "0.2.0"
version = "0.2.1"
author = "WANG"
description = "Community-maintained Nim bindings for the OpenVINO Runtime " &
"C API. Not an official Intel or OpenVINO project."
Expand Down
2 changes: 2 additions & 0 deletions src/openvino/compiled_model.nim
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ proc getProperty*(model: CompiledModel; key: string): string =
##
## Raises `OpenVinoError` when the property is unknown to the device, and
## `OpenVinoArgumentError` if the compiled model is closed.
checkCString(key, "property key")
var native: cstring = nil
checkStatus(ov_compiled_model_get_property(model.handle.native(),
key.cstring, addr native),
Expand All @@ -151,6 +152,7 @@ proc exportTo*(model: CompiledModel; path: string) =
##
## Raises `OpenVinoError` when the path cannot be written or the device does
## not support export.
checkCString(path, "export path")
checkStatus(ov_compiled_model_export_model(model.handle.native(),
path.cstring),
"export compiled model", path)
Expand Down
9 changes: 9 additions & 0 deletions src/openvino/core.nim
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ proc getProperty*(core: Core; device, key: string): string =
## Copies the value and releases OpenVINO's allocation before returning.
##
## Raises `OpenVinoError` for an unknown device or an unsupported property.
checkCString(device, "device name")
checkCString(key, "property key")
var native: cstring = nil
checkStatus(ov_core_get_property(core.handle.native(), device.cstring,
key.cstring, addr native),
Expand All @@ -193,6 +195,7 @@ proc setProperties*(core: Core; device: string;
##
## Raises `OpenVinoError` when the device rejects a property, and
## `OpenVinoArgumentError` if the core is closed.
checkCString(device, "device name")
let native = core.handle.native()
withRawProperties(values, rawProperties, count):
checkStatus(ov_core_set_properties(native, device.cstring, count,
Expand All @@ -210,6 +213,8 @@ proc readModel*(core: Core; modelPath: string; weightsPath = ""): Model =
##
## Raises `OpenVinoArgumentError` when the path does not exist,
## `OpenVinoError` when OpenVINO cannot parse the model.
checkCString(modelPath, "model path")
checkCString(weightsPath, "weights path")
if not fileExists(modelPath):
raiseArgumentError("model file does not exist: " & modelPath)
if weightsPath.len > 0 and not fileExists(weightsPath):
Expand Down Expand Up @@ -259,6 +264,7 @@ proc compileModel*(core: Core; source: Model; device: string;
##
## Raises `OpenVinoError` for an unknown device or a model the device cannot
## take, and `OpenVinoArgumentError` if either object is closed.
checkCString(device, "device name")
let
coreNative = core.handle.native()
modelNative = source.unsafeRawHandle()
Expand All @@ -278,6 +284,8 @@ proc compileModel*(core: Core; modelPath: string; device: string;
## `compileModel`, but without producing a `Model` you would then close.
##
## Raises `OpenVinoArgumentError` when the path does not exist.
checkCString(modelPath, "model path")
checkCString(device, "device name")
if not fileExists(modelPath):
raiseArgumentError("model file does not exist: " & modelPath)
let coreNative = core.handle.native()
Expand Down Expand Up @@ -313,6 +321,7 @@ proc importModel*(core: Core; blob: string; device: string): CompiledModel =
##
## Raises `OpenVinoArgumentError` for an empty blob, `OpenVinoError` when the
## blob is not usable.
checkCString(device, "device name")
if blob.len == 0:
raiseArgumentError("cannot import a compiled model from an empty blob")
var native: ptr ov_compiled_model_t = nil
Expand Down
8 changes: 5 additions & 3 deletions src/openvino/infer_request.nim
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ proc setInputTensor*(request: InferRequest; name: string; value: Tensor) =
##
## Raises `OpenVinoError` when no port has that name, and
## `OpenVinoArgumentError` if either object is closed.
checkCString(name, "tensor name")
checkStatus(ov_infer_request_set_tensor(request.nativeRequest(),
name.cstring,
value.unsafeRawHandle()),
Expand Down Expand Up @@ -450,13 +451,14 @@ proc next*(queue: CompletionQueue; timeout: Duration): Option[int] =
## closed queue.
let milliseconds = timeoutMilliseconds(timeout)
let shared = queue.handle.native()
let deadline = getMonoTime() + initDuration(milliseconds = milliseconds)
let started = getMonoTime()
acquireQueue(shared)
try:
while pendingCount(shared) == 0:
let remaining = (deadline - getMonoTime()).inMilliseconds
if remaining <= 0:
let elapsed = (getMonoTime() - started).inMilliseconds
if elapsed >= milliseconds:
return none(int)
let remaining = milliseconds - elapsed
# Waits in chunks of at most one hour, which the platform waits accept.
waitForCompletion(shared, min(remaining, 3_600_000'i64))
result = some(popCompletion(shared))
Expand Down
2 changes: 2 additions & 0 deletions src/openvino/model.nim
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ proc input*(model: Model; name: string): Port =
## Returns the input port named `name`.
##
## Raises `OpenVinoError` when no input has that name.
checkCString(name, "input name")
var native: ptr ov_output_const_port_t = nil
checkStatus(ov_model_const_input_by_name(model.handle.native(),
name.cstring, addr native),
Expand All @@ -112,6 +113,7 @@ proc output*(model: Model; name: string): Port =
## Returns the output port named `name`.
##
## Raises `OpenVinoError` when no output has that name.
checkCString(name, "output name")
var native: ptr ov_output_const_port_t = nil
checkStatus(ov_model_const_output_by_name(model.handle.native(),
name.cstring, addr native),
Expand Down
13 changes: 11 additions & 2 deletions src/openvino/private/conversions.nim
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import ../raw/core
import ../raw/error
import ../raw/shape

proc checkCString*(value, what: string) =
## Reject embedded terminators before passing a Nim string to C.
if '\0' in value:
raiseArgumentError(what & " contains a NUL character")

proc takeString*(native: var cstring): string =
## Copies an OpenVINO-allocated string and releases the original.
##
Expand Down Expand Up @@ -98,13 +103,17 @@ proc checkedElementCount*(dimensions: openArray[int64]): int64 =
## Raises `OpenVinoArgumentError` on a negative dimension or on overflow.
## Overflow is checked before it happens rather than detected afterwards,
## because a wrapped count would be used to size a buffer.
result = 1
var hasZero = false
for index, dimension in dimensions:
if dimension < 0:
raiseArgumentError("dimension " & $index & " is negative: " &
$dimension)
if dimension == 0:
return 0
hasZero = true
if hasZero:
return 0
result = 1
for dimension in dimensions:
if result > high(int64) div dimension:
raiseArgumentError("shape " & $(@dimensions) &
" overflows a signed 64-bit element count")
Expand Down
3 changes: 3 additions & 0 deletions src/openvino/properties.nim
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
## the kind of thing that silently stops matching after an upstream rename.

import errors
import private/conversions
import raw/property

type Property* = object
Expand All @@ -31,6 +32,8 @@ proc initProperty*(key, value: string): Property =
## otherwise reject with a less specific message.
if key.len == 0:
raiseArgumentError("a property key cannot be empty")
checkCString(key, "property key")
checkCString(value, "property value")
result = Property(key: key, value: value)

proc key*(property: Property): string =
Expand Down
Loading