antfly_embedded/inference.rs
1// Copyright 2026 Antfly, Inc.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Embedded inference without a database: `antfly_inference_open`/`close`
17//! plus the `/ai/v1`-mirroring JSON call surface (embed, rerank, chunk,
18//! generate, generate/batch, rewrite, decide, extract, read, models,
19//! pull). See `zig/CAPI.md`'s "Inference" and "Inference In Process"
20//! sections and the `Embedded inference without a database` block in
21//! `zig/pkg/antfly-embedded/include/antfly.h`.
22//!
23//! [`Inference`] mirrors [`crate::Database`]'s handle-safety story (it is
24//! `Send + Sync`, close waits for in-flight calls and is idempotent/
25//! concurrency-safe, and calls after close fail), but is a separate C ABI
26//! handle kind and registry -- it does not require or share a
27//! [`crate::Database`].
28
29use std::ffi::c_void;
30use std::fmt;
31use std::panic::AssertUnwindSafe;
32use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use antfly_embedded_sys::{
36 self as sys, antfly_buffer, antfly_error_code, antfly_inference, antfly_inference_options,
37 antfly_inference_pull_progress, antfly_slice,
38};
39
40use crate::db::{SUPPORTED_ABI_VERSION, abi_version};
41use crate::error::Error;
42use crate::ffi::{HandleGate, borrow_slice, check, path_to_bytes, take_buffer};
43
44/// Returns the loaded C ABI size of `antfly_inference_options`.
45pub fn inference_options_size() -> u32 {
46 unsafe { sys::antfly_inference_options_size() }
47}
48
49fn compiled_inference_options_size() -> u32 {
50 std::mem::size_of::<antfly_inference_options>() as u32
51}
52
53/// Verifies that the loaded C library matches the header this binding was
54/// compiled against, for the inference handle kind specifically. Every
55/// [`Inference::open`]/[`Inference::open_default`] call checks this first,
56/// like [`crate::validate_abi`] does for [`crate::Database`]. A mismatch is
57/// reported as [`Error::Internal`].
58fn validate_inference_abi() -> crate::Result<()> {
59 if abi_version() != SUPPORTED_ABI_VERSION {
60 return Err(Error::Internal);
61 }
62 if inference_options_size() != compiled_inference_options_size() {
63 return Err(Error::Internal);
64 }
65 Ok(())
66}
67
68// ---------------------------------------------------------------------
69// InferenceError / InferenceResult
70// ---------------------------------------------------------------------
71
72/// An [`Error`] together with the JSON error body an `Inference` JSON call
73/// left behind, when there was one.
74///
75/// Unlike most `*_json` methods elsewhere in this crate, `antfly_inference_*`
76/// calls are documented to always reset and fill their output buffer, even
77/// on failure, with the runtime's JSON error (`{"error":...,"message":...}`)
78/// -- see the "Embedded inference without a database" block in
79/// `zig/pkg/antfly-embedded/include/antfly.h`. This type carries that body forward
80/// instead of discarding it; every buffer is freed (via `antfly_buffer_free`)
81/// either way, whether the call succeeded or not.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct InferenceError {
84 pub error: Error,
85 /// The raw JSON error body, decoded as UTF-8 (lossy). Empty when the
86 /// call never reached the runtime (for example, calling a closed
87 /// handle) and so left no body to report.
88 pub body: String,
89}
90
91impl InferenceError {
92 fn new(error: Error, body: Vec<u8>) -> Self {
93 InferenceError {
94 error,
95 body: String::from_utf8_lossy(&body).into_owned(),
96 }
97 }
98
99 /// The `"message"` field of the JSON error body, if `body` is a JSON
100 /// object with a string `"message"`. Requires the `serde` feature.
101 #[cfg(feature = "serde")]
102 pub fn message(&self) -> Option<String> {
103 let value: serde_json::Value = serde_json::from_str(&self.body).ok()?;
104 value.get("message")?.as_str().map(str::to_owned)
105 }
106}
107
108impl fmt::Display for InferenceError {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 if self.body.is_empty() {
111 fmt::Display::fmt(&self.error, f)
112 } else {
113 write!(f, "{}: {}", self.error, self.body)
114 }
115 }
116}
117
118impl std::error::Error for InferenceError {
119 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
120 Some(&self.error)
121 }
122}
123
124/// A `Result` whose error is [`InferenceError`], returned by `Inference`'s
125/// JSON call methods (as opposed to [`crate::Result`], used by
126/// [`Inference::open`]/[`Inference::close`], which do not produce a JSON
127/// body to report).
128pub type InferenceResult<T> = std::result::Result<T, InferenceError>;
129
130// ---------------------------------------------------------------------
131// InferenceOptions
132// ---------------------------------------------------------------------
133
134/// Configures [`Inference::open`].
135///
136/// All fields default to automatic: an empty `models_dir` uses
137/// `$ANTFLY_INFERENCE_MODELS_DIR`, else `~/.antfly/inference/models`; the
138/// `*_budget_mb` fields default to 0 (automatic/host-detected sizing, the
139/// same knobs as [`crate::OpenOptions`]'s embedded-inference budgets); and
140/// `call_timeout` defaults to `None` (no per-call deadline).
141#[derive(Debug, Clone, Default, PartialEq, Eq)]
142pub struct InferenceOptions {
143 pub models_dir: Option<PathBuf>,
144 pub host_budget_mb: u32,
145 pub backend_budget_mb: u32,
146 pub process_memory_budget_mb: u32,
147 pub combined_budget_mb: u32,
148 pub kv_budget_mb: u32,
149 pub scratch_budget_mb: u32,
150 pub call_timeout: Option<Duration>,
151}
152
153impl InferenceOptions {
154 /// Starts a builder with all defaults (automatic models directory and
155 /// resource budgets, no per-call timeout).
156 pub fn new() -> Self {
157 Self::default()
158 }
159
160 pub fn models_dir(mut self, dir: impl AsRef<Path>) -> Self {
161 self.models_dir = Some(dir.as_ref().to_path_buf());
162 self
163 }
164
165 pub fn host_budget_mb(mut self, mb: u32) -> Self {
166 self.host_budget_mb = mb;
167 self
168 }
169
170 pub fn backend_budget_mb(mut self, mb: u32) -> Self {
171 self.backend_budget_mb = mb;
172 self
173 }
174
175 pub fn process_memory_budget_mb(mut self, mb: u32) -> Self {
176 self.process_memory_budget_mb = mb;
177 self
178 }
179
180 pub fn combined_budget_mb(mut self, mb: u32) -> Self {
181 self.combined_budget_mb = mb;
182 self
183 }
184
185 pub fn kv_budget_mb(mut self, mb: u32) -> Self {
186 self.kv_budget_mb = mb;
187 self
188 }
189
190 pub fn scratch_budget_mb(mut self, mb: u32) -> Self {
191 self.scratch_budget_mb = mb;
192 self
193 }
194
195 /// Deadline applied to each call. `None` (the default) or
196 /// [`Duration::ZERO`] means no deadline. Sub-millisecond durations are
197 /// rounded up, since the C ABI takes whole milliseconds.
198 pub fn call_timeout(mut self, timeout: Duration) -> Self {
199 self.call_timeout = Some(timeout);
200 self
201 }
202
203 fn call_timeout_ms(&self) -> u64 {
204 match self.call_timeout {
205 Some(d) if !d.is_zero() => {
206 let ms = d.as_nanos().div_ceil(1_000_000);
207 u64::try_from(ms).unwrap_or(u64::MAX)
208 }
209 _ => 0,
210 }
211 }
212}
213
214// ---------------------------------------------------------------------
215// PullProgress
216// ---------------------------------------------------------------------
217
218/// One report from an [`Inference::pull`] progress callback. Owned (copied
219/// out of the C ABI's borrowed, callback-lifetime-only struct) so it can be
220/// used freely -- stored, sent across threads, etc. -- without carrying a
221/// lifetime tied to the callback invocation.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct PullProgress {
224 /// The model reference being pulled (one per requested variant).
225 pub model: String,
226 pub file: String,
227 pub bytes_downloaded: u64,
228 /// 0 when unknown.
229 pub total_bytes: u64,
230 pub files_done: u64,
231 pub files_total: u64,
232 /// The file was already present and verified; nothing was downloaded.
233 pub cached: bool,
234}
235
236impl PullProgress {
237 /// # Safety
238 /// `raw`'s `model`/`file` slices must point at initialized memory valid
239 /// for the duration of this call (upheld because this is only ever
240 /// called from the trampoline libantfly invokes synchronously, on the
241 /// slices it just populated for that one call).
242 unsafe fn from_raw(raw: &antfly_inference_pull_progress) -> Self {
243 PullProgress {
244 model: unsafe { slice_to_string(raw.model) },
245 file: unsafe { slice_to_string(raw.file) },
246 bytes_downloaded: raw.bytes_downloaded,
247 total_bytes: raw.total_bytes,
248 files_done: raw.files_done,
249 files_total: raw.files_total,
250 cached: raw.cached,
251 }
252 }
253}
254
255/// # Safety
256/// `slice` must point at `slice.len` initialized bytes, or have a null/
257/// zero-length pointer.
258unsafe fn slice_to_string(slice: antfly_slice) -> String {
259 if slice.ptr.is_null() || slice.len == 0 {
260 return String::new();
261 }
262 let bytes = unsafe { std::slice::from_raw_parts(slice.ptr, slice.len) };
263 String::from_utf8_lossy(bytes).into_owned()
264}
265
266// ---------------------------------------------------------------------
267// Inference
268// ---------------------------------------------------------------------
269
270/// An embedded inference runtime handle, with no database. Models load on
271/// first use and stay cached until the handle closes.
272///
273/// `Inference` is `Send + Sync` and safe for concurrent use from any
274/// thread, exactly like [`crate::Database`]: libantfly's inference handles
275/// have the same "close waits for in-flight calls, a closed or foreign
276/// handle is rejected" contract. See `zig/CAPI.md`'s "Inference In
277/// Process" section for what running on a GPU/driver backend means for
278/// `call_timeout`/close/process-fault behavior: once a call reaches the
279/// device or driver it runs to completion, and a driver fault terminates
280/// the process.
281pub struct Inference {
282 gate: HandleGate<antfly_inference>,
283}
284
285// SAFETY: see the identical justification on `Database` in `db.rs` --
286// libantfly's `antfly_inference` handles share the same "serialized"
287// threading contract as `antfly_db` handles (zig/CAPI.md "Thread Safety"),
288// and `HandleGate` only prevents calling into a handle after
289// `antfly_inference_close` has returned.
290unsafe impl Send for Inference {}
291unsafe impl Sync for Inference {}
292
293impl Inference {
294 fn from_handle(handle: *mut antfly_inference) -> Inference {
295 Inference {
296 gate: HandleGate::new(handle),
297 }
298 }
299
300 fn with_handle<R>(
301 &self,
302 f: impl FnOnce(*mut antfly_inference) -> crate::Result<R>,
303 ) -> crate::Result<R> {
304 self.gate.with_handle(f)
305 }
306
307 /// Runs a no-input `*_json` call (currently just `list_models`),
308 /// wrapping the outcome in [`InferenceResult`] per [`InferenceError`]'s
309 /// doc comment.
310 fn read_buffer(
311 &self,
312 f: impl FnOnce(*mut antfly_inference, *mut antfly_buffer) -> antfly_error_code,
313 ) -> InferenceResult<Vec<u8>> {
314 let raw = self.with_handle(|handle| {
315 let mut out = antfly_buffer::default();
316 let code = f(handle, &mut out);
317 let body = unsafe { take_buffer(out) };
318 Ok((code, body))
319 });
320 finish(raw)
321 }
322
323 /// Runs a `*_json` call that takes a request body, wrapping the outcome
324 /// in [`InferenceResult`] per [`InferenceError`]'s doc comment.
325 fn call_json(
326 &self,
327 request: &[u8],
328 f: impl FnOnce(*mut antfly_inference, antfly_slice, *mut antfly_buffer) -> antfly_error_code,
329 ) -> InferenceResult<Vec<u8>> {
330 let raw = self.with_handle(|handle| {
331 let mut out = antfly_buffer::default();
332 let code = f(handle, borrow_slice(request), &mut out);
333 let body = unsafe { take_buffer(out) };
334 Ok((code, body))
335 });
336 finish(raw)
337 }
338
339 // -- Open / close -----------------------------------------------------
340
341 /// Opens an embedded inference runtime using explicit options.
342 pub fn open(options: &InferenceOptions) -> crate::Result<Inference> {
343 validate_inference_abi()?;
344
345 let mut c_opts: antfly_inference_options = unsafe { std::mem::zeroed() };
346 check(unsafe { sys::antfly_inference_options_init(&mut c_opts) })?;
347
348 // `models_dir_bytes` must outlive the `antfly_inference_open` call
349 // below, since `c_opts.models_dir` only borrows it.
350 let models_dir_bytes = options.models_dir.as_deref().map(path_to_bytes);
351 if let Some(bytes) = &models_dir_bytes {
352 c_opts.models_dir = borrow_slice(bytes);
353 }
354 c_opts.host_budget_mb = options.host_budget_mb;
355 c_opts.backend_budget_mb = options.backend_budget_mb;
356 c_opts.process_memory_budget_mb = options.process_memory_budget_mb;
357 c_opts.combined_budget_mb = options.combined_budget_mb;
358 c_opts.kv_budget_mb = options.kv_budget_mb;
359 c_opts.scratch_budget_mb = options.scratch_budget_mb;
360 c_opts.call_timeout_ms = options.call_timeout_ms();
361
362 let mut handle: *mut antfly_inference = std::ptr::null_mut();
363 check(unsafe { sys::antfly_inference_open(&c_opts, &mut handle) })?;
364 Ok(Inference::from_handle(handle))
365 }
366
367 /// Opens an embedded inference runtime with every default: models
368 /// directory from `$ANTFLY_INFERENCE_MODELS_DIR`/
369 /// `~/.antfly/inference/models`, automatic resource budgets, no
370 /// per-call timeout. Equivalent to `antfly_inference_open(NULL, ...)`.
371 pub fn open_default() -> crate::Result<Inference> {
372 validate_inference_abi()?;
373 let mut handle: *mut antfly_inference = std::ptr::null_mut();
374 check(unsafe { sys::antfly_inference_open(std::ptr::null(), &mut handle) })?;
375 Ok(Inference::from_handle(handle))
376 }
377
378 /// Releases the embedded inference handle, waiting for in-flight calls
379 /// on other threads to finish first -- including any in-progress
380 /// [`Inference::pull`] or [`Inference::generate_stream`], neither of
381 /// which `close` itself cancels (their own progress/chunk callbacks can,
382 /// by returning `false`). Idempotent and safe to call concurrently with
383 /// itself or from several threads at once; calls made after (or racing)
384 /// `close` fail. Takes `&self`, not `self`, for the same reason as
385 /// [`crate::Database::close`]. [`Drop`] also closes, for callers who
386 /// never need to close early.
387 pub fn close(&self) -> crate::Result<()> {
388 self.gate
389 .close(|handle| unsafe { sys::antfly_inference_close(handle) });
390 Ok(())
391 }
392
393 // -- JSON calls ---------------------------------------------------------
394
395 /// `POST /embed`.
396 pub fn embed(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
397 self.call_json(request.as_ref(), |h, req, out| unsafe {
398 sys::antfly_inference_embed_json(h, req, out)
399 })
400 }
401
402 /// `POST /rerank`.
403 pub fn rerank(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
404 self.call_json(request.as_ref(), |h, req, out| unsafe {
405 sys::antfly_inference_rerank_json(h, req, out)
406 })
407 }
408
409 /// `POST /chunk`.
410 pub fn chunk(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
411 self.call_json(request.as_ref(), |h, req, out| unsafe {
412 sys::antfly_inference_chunk_json(h, req, out)
413 })
414 }
415
416 /// `POST /generate`. A request with `"stream": true` fails with
417 /// [`Error::InvalidArgument`]: responses from this method are always
418 /// complete. Use [`Inference::generate_stream`] to stream.
419 pub fn generate(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
420 self.call_json(request.as_ref(), |h, req, out| unsafe {
421 sys::antfly_inference_generate_json(h, req, out)
422 })
423 }
424
425 /// Streams a generate request (the same body as [`Inference::generate`];
426 /// `"stream"` is set for the caller). `on_chunk` is called on the
427 /// calling thread for each chunk -- the JSON of a `chat.completion.chunk`,
428 /// valid only for the duration of the call -- as the model produces
429 /// tokens; generation waits for each call to return before producing
430 /// the next chunk.
431 ///
432 /// Returning `false` from `on_chunk` stops generation and this method
433 /// returns [`Error::Cancelled`] (wrapped in [`InferenceError`]);
434 /// cancellation is always honored at the chunk where `on_chunk` returns
435 /// `false`. A request rejected before generation starts (for example a
436 /// missing model) fails like
437 /// [`Inference::generate`], with the JSON error body attached; a
438 /// failure mid-stream fails with [`Error::Internal`] and a JSON body
439 /// naming `"STREAM_FAILED"`.
440 ///
441 /// A panic inside `on_chunk` is caught and does not unwind across the C
442 /// ABI boundary (unwinding through `extern "C"` is undefined behavior):
443 /// it cancels the stream (as if `on_chunk` had returned `false`) and is
444 /// resumed once the underlying call returns.
445 pub fn generate_stream(
446 &self,
447 request: impl AsRef<[u8]>,
448 on_chunk: &mut dyn FnMut(&[u8]) -> bool,
449 ) -> InferenceResult<()> {
450 // Same shape as `pull`'s callback plumbing below: a type-erased
451 // closure plus a slot to stash a panic payload so it can be resumed
452 // after the FFI call returns instead of unwinding through
453 // `extern "C"`.
454 struct CallbackCtx<'a> {
455 on_chunk: &'a mut dyn FnMut(&[u8]) -> bool,
456 panic: Option<Box<dyn std::any::Any + Send>>,
457 }
458
459 unsafe extern "C" fn trampoline(ctx: *mut c_void, chunk_json: antfly_slice) -> bool {
460 if ctx.is_null() {
461 return true;
462 }
463 let ctx = unsafe { &mut *ctx.cast::<CallbackCtx>() };
464 if ctx.panic.is_some() {
465 // A previous invocation already panicked; stop the stream
466 // and don't call into (possibly now-invalid) user code
467 // again before we get a chance to resume that panic.
468 return false;
469 }
470 let bytes: &[u8] = if chunk_json.ptr.is_null() || chunk_json.len == 0 {
471 &[]
472 } else {
473 unsafe { std::slice::from_raw_parts(chunk_json.ptr, chunk_json.len) }
474 };
475 let result = std::panic::catch_unwind(AssertUnwindSafe(|| (ctx.on_chunk)(bytes)));
476 match result {
477 Ok(cont) => cont,
478 Err(payload) => {
479 ctx.panic = Some(payload);
480 false
481 }
482 }
483 }
484
485 let raw = self.with_handle(|handle| {
486 let mut out = antfly_buffer::default();
487 let mut ctx = CallbackCtx {
488 on_chunk,
489 panic: None,
490 };
491 let ctx_ptr = std::ptr::addr_of_mut!(ctx).cast::<c_void>();
492
493 let code = unsafe {
494 sys::antfly_inference_generate_stream_json(
495 handle,
496 borrow_slice(request.as_ref()),
497 Some(trampoline),
498 ctx_ptr,
499 &mut out,
500 )
501 };
502 let body = unsafe { take_buffer(out) };
503
504 if let Some(payload) = ctx.panic.take() {
505 std::panic::resume_unwind(payload);
506 }
507
508 Ok((code, body))
509 });
510
511 match raw {
512 Ok((code, _body)) if code == sys::ANTFLY_OK => Ok(()),
513 Ok((code, body)) => Err(InferenceError::new(Error::from_code(code), body)),
514 Err(e) => Err(InferenceError::new(e, Vec::new())),
515 }
516 }
517
518 /// `POST /generate/batch`: up to 128 non-streaming generate requests in
519 /// one call; per-item failures are reported in the response body, not
520 /// as an `Err`.
521 pub fn generate_batch(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
522 self.call_json(request.as_ref(), |h, req, out| unsafe {
523 sys::antfly_inference_generate_batch_json(h, req, out)
524 })
525 }
526
527 /// `POST /rewrite`.
528 pub fn rewrite(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
529 self.call_json(request.as_ref(), |h, req, out| unsafe {
530 sys::antfly_inference_rewrite_json(h, req, out)
531 })
532 }
533
534 /// Answers named choice, ordinal score, and Boolean questions.
535 /// `POST /decisions`; accepts DecideRequest and returns DecideResponse JSON
536 /// from `specs/openapi/inference/api.yaml`. Models must support typed decisions.
537 pub fn decide(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
538 self.call_json(request.as_ref(), |h, req, out| unsafe {
539 sys::antfly_inference_decide_json(h, req, out)
540 })
541 }
542
543 /// `POST /extract`.
544 pub fn extract(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
545 self.call_json(request.as_ref(), |h, req, out| unsafe {
546 sys::antfly_inference_extract_json(h, req, out)
547 })
548 }
549
550 /// `POST /read` for images, documents, or audio.
551 pub fn read(&self, request: impl AsRef<[u8]>) -> InferenceResult<Vec<u8>> {
552 self.call_json(request.as_ref(), |h, req, out| unsafe {
553 sys::antfly_inference_read_json(h, req, out)
554 })
555 }
556
557 /// `GET /models`: the installed models.
558 pub fn list_models(&self) -> InferenceResult<Vec<u8>> {
559 self.read_buffer(|h, out| unsafe { sys::antfly_inference_list_models_json(h, out) })
560 }
561
562 /// Downloads a model from the Hugging Face Hub into the handle's models
563 /// directory, like `antfly inference pull`. `request` is documented on
564 /// `antfly_inference_pull_json` in `zig/pkg/antfly-embedded/include/antfly.h`
565 /// (`{"model": "owner/name[:variant]", ...}`).
566 ///
567 /// `progress`, if given, is called synchronously on the calling thread
568 /// as each file starts, every 16 MiB, and as it completes; the download
569 /// waits for each call to return before continuing. Returning `false`
570 /// cancels the pull: this method then fails with [`Error::Cancelled`]
571 /// (wrapped in [`InferenceError`]) and the model is not installed.
572 /// Cancellation takes effect at the report where `progress` returns
573 /// `false` -- it is always honored, even at the very last report -- not
574 /// before. Completed files stay staged, so pulling the same model again
575 /// resumes rather than restarts. A panic inside `progress` is caught
576 /// and does not unwind across the C ABI boundary (unwinding through
577 /// `extern "C"` is undefined behavior): it cancels the pull (as if `progress` had
578 /// returned `false`) and is resumed once the underlying
579 /// `antfly_inference_pull_json` call returns.
580 ///
581 /// [`Inference::close`] waits for a pull in progress. On success the
582 /// response is `{"models": [...], "models_dir": "..."}`; a model
583 /// missing from the hub fails with [`Error::NotFound`], a bad request
584 /// or a model over the configured size limits with
585 /// [`Error::InvalidArgument`], and a network or hub failure with
586 /// [`Error::Busy`].
587 pub fn pull(
588 &self,
589 request: impl AsRef<[u8]>,
590 progress: Option<&mut dyn FnMut(&PullProgress) -> bool>,
591 ) -> InferenceResult<Vec<u8>> {
592 // Carries the caller's closure (type-erased behind the trait
593 // object) plus a slot to stash a panic payload if it panics, so the
594 // panic can be resumed after the FFI call returns instead of
595 // unwinding through `extern "C"` (undefined behavior).
596 struct CallbackCtx<'a> {
597 progress: &'a mut dyn FnMut(&PullProgress) -> bool,
598 panic: Option<Box<dyn std::any::Any + Send>>,
599 }
600
601 unsafe extern "C" fn trampoline(
602 ctx: *mut c_void,
603 raw: *const antfly_inference_pull_progress,
604 ) -> bool {
605 if ctx.is_null() || raw.is_null() {
606 return true;
607 }
608 let ctx = unsafe { &mut *ctx.cast::<CallbackCtx>() };
609 if ctx.panic.is_some() {
610 // A previous invocation already panicked; cancel and don't
611 // call into (possibly now-invalid) user code again before we
612 // get a chance to resume that panic.
613 return false;
614 }
615 let progress = unsafe { PullProgress::from_raw(&*raw) };
616 let result = std::panic::catch_unwind(AssertUnwindSafe(|| (ctx.progress)(&progress)));
617 match result {
618 Ok(cont) => cont,
619 Err(payload) => {
620 ctx.panic = Some(payload);
621 false
622 }
623 }
624 }
625
626 let raw = self.with_handle(|handle| {
627 let mut out = antfly_buffer::default();
628
629 // The context must stay at one address for the whole call: build
630 // it in its final place, then take the pointer the callback uses.
631 let mut callback_ctx = progress.map(|f| CallbackCtx {
632 progress: f,
633 panic: None,
634 });
635 let (progress_fn, progress_ctx): (sys::antfly_inference_pull_progress_fn, *mut c_void) =
636 match callback_ctx.as_mut() {
637 Some(ctx) => (
638 Some(trampoline as _),
639 std::ptr::from_mut(ctx).cast::<c_void>(),
640 ),
641 None => (None, std::ptr::null_mut()),
642 };
643
644 let code = unsafe {
645 sys::antfly_inference_pull_json(
646 handle,
647 borrow_slice(request.as_ref()),
648 progress_fn,
649 progress_ctx,
650 &mut out,
651 )
652 };
653 let body = unsafe { take_buffer(out) };
654
655 if let Some(ctx) = &mut callback_ctx
656 && let Some(payload) = ctx.panic.take()
657 {
658 std::panic::resume_unwind(payload);
659 }
660
661 Ok((code, body))
662 });
663 finish(raw)
664 }
665}
666
667/// Turns the outcome of a raw call (`Ok((code, body))` for anything that
668/// actually reached the C ABI, `Err(e)` only when [`HandleGate::with_handle`]
669/// itself refused the call, e.g. because the handle is closed) into
670/// [`InferenceResult`].
671fn finish(raw: crate::Result<(antfly_error_code, Vec<u8>)>) -> InferenceResult<Vec<u8>> {
672 match raw {
673 Ok((code, body)) if code == sys::ANTFLY_OK => Ok(body),
674 Ok((code, body)) => Err(InferenceError::new(Error::from_code(code), body)),
675 Err(e) => Err(InferenceError::new(e, Vec::new())),
676 }
677}
678
679impl Drop for Inference {
680 fn drop(&mut self) {
681 let _ = self.close();
682 }
683}
684
685impl std::fmt::Debug for Inference {
686 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
687 f.debug_struct("Inference")
688 .field("open", &self.gate.is_open())
689 .finish()
690 }
691}