Skip to content

Bug fixes - #184

Merged
wangvsa merged 45 commits into
mainfrom
bug_fixes
Oct 19, 2026
Merged

wangvsa merged 45 commits into
mainfrom
bug_fixes

Conversation

@JaeseungYeom

Copy link
Copy Markdown
Contributor

various bug fixes

The fix makes dyad_release_flock() construct a complete unlock request before calling fcntl(F_SETLKW).

Some close paths pass a struct flock that was never used when acquiring the lock, so its range fields may be uninitialized. Previously, the function changed only:

lock->l_type = F_UNLCK;

That could pass garbage l_whence, l_start, or l_len to fcntl, leading to an invalid or partial unlock.

The staged change sets:

lock->l_whence = SEEK_SET;
lock->l_start = 0;
lock->l_len = 0;

This means “unlock the whole file,” matching DYAD’s full-file shared/exclusive lock acquisition. It also sets l_pid to the context PID; that field is ignored for F_SETLKW, but makes the struct fully initialized.
Margo remote addresses are owned by the DTL address cache. The inline
request field, remote_addr, and worker-offloaded request state both hold
borrowed pointers to cache entries.

Before this change, inline request handling could leave remote_addr
pointing to a cached address at shutdown. dyad_dtl_margo_finalize() freed
that pointer directly, then freed the same address again while tearing
down addr_cache, causing a double-free.

Remove the direct remote_addr free and make the cache teardown loop the
sole Margo address owner. Update ownership comments and finalizer
documentation to describe remote_addr as a borrowed cache pointer.

The existing Flux Margo producer/consumer CI path uses worker-offloaded
request handling, which clears the shared remote_addr field. It does not
reproduce this inline-request finalization defect. A focused regression
test for inline request finalization is still needed.
Check flux_request_unpack() for failure before converting the cons_buf
string with atoll(). A malformed or incompatible RPC payload can leave
the string pointer NULL; parsing it first dereferences NULL and crashes
the broker instead of returning DYAD_RC_BADUNPACK.
Prevent UCX and Margo consumers from waiting indefinitely after a producer
has accepted a fetch request but cannot provide its data.

Reserve DYAD_DTL_SEND_ERROR (SIZE_MAX) as an internal send-length sentinel,
while preserving size_t byte-count interfaces. Translate that sentinel in
each transport backend:

- UCX writes an ssize_t -1 length prefix into the consumer’s registered
  buffer.
- Margo sends a control RPC with n = -1 and no bulk transfer.
- Flux RPC consumes the detached request state without sending raw data;
  the existing Flux stream error remains its failure notification.

Route whole-file and range-fetch producer failures through the established
DTL connection/send flow, including detached range requests. This covers
open, read, allocation, and mid-transfer failures without changing the
success-path transfer protocol.

Make Margo receive publication thread-safe with C11 atomics. The Margo
progress handler publishes data or failure state with a release store to
recv_ready; the consumer observes it with an acquire load and returns
DYAD_RC_BADFIO for the n = -1 marker without allocating or pulling bulk
data.

Add and update Doxygen documentation for the DTL failure sentinel, Margo
receive state, and affected transport APIs.
Initialize all Margo resource fields to documented invalid values immediately
after allocating dyad_dtl_margo_t and before any staged initialization step can
enter shared cleanup.

This makes failure handling safe when protocol validation, margo_init(), RPC
registration, or local-address acquisition fails before initialization
completes. Finalization now frees the local Margo address only when it was
successfully acquired.

Prevents invalid Margo-handle/address cleanup and crashes for invalid
DYAD_MARGO_PROTO configurations.
Derive read/write intent in the open() and open64() GOTCHA wrappers from
oflag & O_ACCMODE instead of the variadic creation-permission argument.

The optional mode argument contains permission bits for O_CREAT (for example
0644); it is not an access mode. The prior checks accidentally treated its
default value of zero as O_RDONLY and compared permissions with O_WRONLY and
O_APPEND.

This ensures only genuine read-only opens trigger DYAD consumption and that
all writable opens receive the producer-side exclusive lock.
Replace the undefined filename identifier with filepath in the C++17
basic_ofstream_dyad filesystem-path constructor.

This restores compilation when DYAD_HAS_STD_FSTREAM_FD is enabled and
the template is parsed or instantiated with std::filesystem support.
Replace the ofstream-specific lock and unlock macros used by
basic_fstream_dyad with their fstream-specific counterparts.

basic_fstream_dyad stores std::basic_fstream objects. When
DYAD_HAS_STD_FSTREAM_FD is enabled, the old macros expanded to helpers that
accept std::basic_ofstream references, which is a different C++ stream type
and causes compilation to fail when the affected fstream paths are
instantiated.

This is a type-correctness fix only; it does not change DYAD’s supported I/O
modes or add read/write behavior.
Add DYAD_WORKER_LOG_* macros for code that may execute on DYAD’s
range-fetch worker pool.

With the Flux logger, normal DYAD_LOG_* macros call flux_log() on the
module’s Flux handle. That handle belongs to the reactor thread, but range
workers reach those macros indirectly through range-cache and shared-lock
helpers. A worker could therefore use the reactor-owned Flux handle while
the reactor was processing other events.

Route worker-reachable range-cache, shared-lock, and unlock diagnostics to
stderr in Flux builds. Flux redirects module stderr to the rank-0 log, so
messages remain immediate and centrally available without accessing the
Flux handle from a worker thread.

For CPP_LOGGER and other non-Flux configurations, DYAD_WORKER_LOG_* aliases
the existing DYAD_LOG_* backend. The no-logging configuration remains a
no-op. No transfer-path locks, queues, allocations, or runtime thread checks
are added.
A range fetch creates a sparse local file with the origin file’s full logical
size, then records only fetched blocks in its .dyad_cached bitmap. Whole-file
paths previously used a positive file size as proof that the file was fully
available, causing them to treat sparse holes as valid data and silently
return zeros for unfetched ranges.

Add range-cache helpers to determine whether every data block is marked
present and to mark an existing bitmap complete after a successful full-file
transfer.

Use the completeness check in both whole-file consumer paths. If a bitmap
shows a partial cache, fetch the whole file rather than accepting its sparse
size; then mark the bitmap complete. The producer whole-file handler now
detects a partial origin-backed cache and fills its missing blocks before
sending the file.

Add a range-cache unit regression test covering a partially populated bitmap
and completion marking.
Exclude .dyad_cached bitmap sidecars from cache eviction candidates and cache
capacity accounting. A bitmap is metadata for its corresponding data file,
not an independently evictable cache object.

When evicting a range-cached data file, remove its bitmap sidecar as part of
the same eviction. This prevents a later range request from finding stale
bitmap bits that claim missing data is already cached.

Hold an exclusive advisory lock on the local data file while a range-cache
miss writes its fetched span. The evictor already takes a nonblocking
exclusive lock before unlinking a victim, so it now skips a file being
updated instead of unlinking it mid-write.

Use the worker-safe logger for exclusive-lock diagnostics, since range-cache
workers now acquire that lock as well.
Set Dyad.initialized after a successful init_env() call.

init_env() completed native DYAD initialization but left the Python-side guard
false. As a result, finalize() returned immediately and never called
dyad_finalize(), leaking the Flux handle, DTL state, and cache-policy
resources for users of the environment-based initialization path.

This matches init() and allows finalize() to perform native cleanup exactly
once.
Route Flux handle-open and rank-query failures through the shared
initialization cleanup path.

After any failed initialization stage, reset the context to its default state
with initialized and reenter cleared. This prevents later dyad_init() calls
from treating a failed, partially initialized context as usable.

Return the original initialization error instead of unconditionally returning
DYAD_RC_NOCTX, so callers can distinguish Flux failures from other setup
errors.
Track whether DYAD opened the Flux handle stored in its context.

When dyad_init() receives a Flux handle from its caller, DYAD borrows that
handle and must not close it. Previously dyad_clear() unconditionally called
flux_close(), allowing a module or application finalization path to close a
handle still owned by Flux or the caller.

Set owns_flux_handle only after a successful flux_open() call. Finalization
now closes only handles opened by DYAD and always clears the stored pointer.

Update the Python ctypes context layout for the added ownership field.
Route the dyad_consume() write-descriptor open failure through the normal
cleanup path after releasing the exclusive lock on the local file.

Previously this error jumped directly to the final return path while leaving
lock_fd open and locked. Other consumers of the same file could then block
until process exit. Centralize metadata cleanup at consume_done as well, so
metadata obtained before this failure is not leaked.
Validate the DYAD context in dyad_produce() before assigning ctx->fname or
issuing context-backed logging.

Guard cleanup-path writes to ctx->reenter in whole-file, metadata, and range
consume operations so a null-context error returns DYAD_RC_NOCTX instead of
dereferencing the null pointer. Also guard the directory-sync reentry-state
backup before reading ctx->reenter.

Use stderr for the null-context producer diagnostic because Flux logging
requires a valid DYAD context and Flux handle.
Parse DYAD_KEY_BINS and DYAD_SERVICE_MUX with strtoul() instead of atoi().

Accept only nonzero decimal values representable as unsigned int. Invalid,
empty, negative, zero, and overflowing values now use the existing defaults:
1024 key bins and service mux 1.

This prevents DYAD_KEY_BINS=0 or nonnumeric input from reaching modulo-by-zero
code and prevents values such as DYAD_SERVICE_MUX=-1 from wrapping to a large
unsigned value that maps every rank to node index zero.
Ensure dyad_consume_w_metadata() closes lock_fd on every error path after it
has acquired the exclusive file lock.

Route post-lock failures through consume_done, release the lock when opening
the write descriptor fails, and correct the store-failure path to unlock
lock_fd instead of io_fd, which has already been closed.

This prevents leaked descriptors and process-held fcntl locks that could
block later consumers of the same file indefinitely.
mkdir_as_needed() temporarily sets the process umask to zero so mkpath() can
create directories with the requested mode.

Several error and concurrent-creation paths returned before restoring the
previous umask. A process that encountered one of those paths retained umask
zero, causing later unrelated file and directory creations to receive overly
permissive permissions.

Restore the saved umask before every return after the temporary umask change,
while preserving the existing successful directory-creation behavior.
Use st_blocks in POSIX 512-byte units when measuring cache entries and
available space during eviction.

Range caching creates sparse files whose st_size reflects the full origin
file, even when only requested ranges consume local storage. Counting st_size
therefore overstates cache usage and can trigger unnecessary eviction.

Measure allocated blocks instead so cache capacity reflects actual disk usage
while retaining the existing eviction policy.
Update cache scan and eviction tests to derive expected usage and capacity
from st_blocks in POSIX 512-byte units instead of logical file size.

This matches sparse range-cache behavior, where st_size represents the full
logical file while only fetched ranges consume local disk space. Also reset
the child process SIGTERM handler in the locked-entry test so its deliberate
termination is not interpreted as a Catch2 test failure.
Recursively scan real subdirectories of the managed cache path so nested
regular files contribute to cache capacity and can be evicted.

Continue skipping cache lock files and range-cache bitmap sidecars at every
directory level, and do not traverse symlinked directories.

Add regression coverage for nested data files and bitmap sidecars.
Define DYAD_RESTRICT in the generated configuration header and replace raw
restrict, __restrict__, and __restrict__ qualifiers throughout DYAD.

Use standard restrict for C, Intel __restrict for Intel C++, and
__restrict__ for GNU and Clang C++. This keeps shared C/C++ declarations
portable and uses one consistent spelling across the project.
Add cache-specific open-file-description lock helpers using F_OFD_SETLK and
F_OFD_SETLKW. Unlike process-owned POSIX record locks, OFD locks prevent
same-process cache workers from acquiring conflicting locks and ensure that
closing one descriptor cannot release another worker's lock.

Use the new helpers for cache eviction, range-cache data writes, and bitmap
updates while retaining the existing lock helpers for normal producer and
consumer paths. OFD locks continue to conflict with those traditional locks,
so eviction still skips normally locked files.

Add regression coverage for same-process descriptor contention and
interoperability with existing DYAD locks.

Future migration plan: migrate the remaining traditional fcntl() helpers to OFD locks after auditing for same-process re-locking, dup()/fork() ownership, and cleanup paths that rely on close-based release. Validate thread and multi-process contention on supported Linux filesystems, then remove the cache-specific OFD helpers once the common lock helpers provide OFD semantics.
Transfer ownership of decoded remote UCX addresses to newly created endpoint-cache entries. Keep each address valid until its endpoint has fully disconnected, then release it during cache removal or finalization.

Free per-request addresses normally on cache hits and failed setup paths, and clean up any partially created endpoint if cache insertion fails.

Validated with the UCX build and a live two-rank Flux producer/consumer teardown test.
Propagate UCX transfer-buffer allocation failures from DTL initialization.

When memory query or remote-key packing fails after a successful map, unmap the buffer once and clear the memory handle, buffer pointer, and derived remote address. This prevents finalization from double-unmapping released UCX memory or using stale buffer state.

Validated with UCX builds, live two-rank transfer, and forced allocation-failure cleanup.
Perform the UCX startup loopback with a temporary one-byte RDMA buffer. Register that buffer with local-read and remote-write access, pack and unpack a self key, issue a one-byte self ucp_put_nbx(), then release the key, unmap the buffer, and close the self endpoint.

Keep the normal producer transfer buffer registered as local-read-only.
The C++ stream core previously marked itself initialized even when the
first-time DYAD setup failed. Subsequent stream operations could then use
an invalid context and crash.

Abort from both stream-core initialization paths unless DYAD produced a
usable Flux context. This preserves the intended one-time, thread-local
DYAD setup performed by the first C++ stream object while preventing
execution from continuing with invalid synchronization state.
Move m_filename along with the underlying stream and DYAD core in
ofstream_dyad and fstream_dyad move constructors and assignments.

Without this, a moved-to stream closed its real file but called
close_sync(""), so DYAD did not publish metadata for the file and
consumers could not retrieve it.

Add a live UCX regression covering publication and consumption after both
move construction and move assignment.
Add reusable OFD lock helpers and use them for whole-file consumer
coordination. This keeps the consumer's lock associated with lock_fd, so
closing the separate io_fd cannot release it accidentally.

Extend dyad_consume() with an is_managed output used by the GOTCHA wrapper
to identify successful managed read opens without repeating its path
classification. Keep dyad_consume_w_metadata() on its existing
three-argument API.

Take shared OFD locks on successfully opened managed reader descriptors in
the C wrapper and C++ ifstream wrapper. The lock now lives exactly as long
as the application descriptor and is released automatically on close.
Retain the producer's existing POSIX locks; POSIX and OFD record locks
conflict, preserving producer/consumer synchronization.

Add C and C++ reader-lock regressions covering open(), fopen(), ifstream
constructors, and explicit ifstream open(). Each verifies that a separate
process cannot take an exclusive POSIX lock while the reader is open, but
can do so after it closes.

Document the remaining consume-to-reader handoff interval and the
guard-descriptor direction for a later, separate change.
Keep dyad_consume()'s lock_fd locked through cache eviction after a
successful whole-file consume. Downgrade its exclusive OFD lock to a
shared guard and return that descriptor to the immediate reader-open
caller.

After the GOTCHA wrapper or C++ ifstream path successfully opens the real
application descriptor, acquire its shared OFD lock before closing the
guard. The overlapping shared locks prevent cache eviction between
consume completion and the application reader lock. If the real open
fails, close the transferred guard without publishing a producer event.

Extend dyad_consume() with an optional guard_fd output and propagate it
through dyad_stream_core::open_sync(). Keep dyad_consume_w_metadata() on
its existing API.

Update the reader-lock handoff documentation and retain the C and C++
reader-lock regressions.
Extend the C wrapper reader-lock regression to verify that cache eviction
cannot acquire its exclusive OFD lock while dyad_consume()'s transferred
shared guard is held. Verify that the application reader lock continues
to block eviction after the guard closes, and that eviction proceeds after
reader close.

Also verify that a failed intercepted open releases its transferred guard.
Update the standalone regression build instructions with its DYAD client,
utility, and context link dependencies.
Update consumer-lock documentation to show that dyad_consume() retains its
exclusive OFD lock through metadata retrieval, transfer, and cache eviction,
then downgrades it to a shared guard for the real reader open.

Refresh the C GOTCHA and C++ ifstream documentation, reader-lock regression
instructions, and locking-flow diagram to show the overlapping guard and
application-reader locks. Clarify that producer POSIX locks conflict with
consumer OFD locks and that both remain cooperative.
@JaeseungYeom JaeseungYeom self-assigned this Oct 19, 2026
@JaeseungYeom JaeseungYeom added the bug Something isn't working label Oct 19, 2026
Handle consumer-side Margo receive failures without relying on assertions.

The Margo data-ready callback now checks receive-buffer allocation, bulk
registration, and RDMA-pull results. On failure, it releases acquired
resources, publishes the consumer failure state, wakes the waiting consumer,
and returns a nonzero result through the existing Margo RPC response.

Make the producer inspect that response so a failed consumer-side transfer is
not reported as a successful send. The existing request/response exchange is
reused; no additional communication is added to the successful transfer path.
When a range-fetch worker completes file I/O but its detached Flux-RPC data
response fails, return ECOMM through the streaming RPC instead of ENODATA.

ENODATA is DYAD’s clean end-of-stream marker. Returning it after
flux_respond_raw() fails could make the consumer accept an undelivered range
as a successful empty result. Preserve ENODATA for successful sends and use
ECOMM only on the existing failure path.
Return an allocated DTL buffer from the whole-file and range-fetch synchronous
error paths before responding to the consumer.

Flux RPC and Margo allocate these buffers dynamically, so failures after
get_buffer() previously leaked one buffer per failed request. Preserve the
original errno across cleanup so the consumer still receives the correct
failure result.
Detect zero and negative producer file sizes before allocating a DTL buffer.
Preserve errno from a failed size query, and report an empty whole-file fetch
as EIO.

This prevents Flux from rejecting a zero-valued error response, which left the
consumer waiting without a terminal result. UCX and Margo retain their
existing producer-failure notifications
Recognize binary read-only and write-only stream modes in the fopen() and
fopen64() wrappers without precomputing mode state on unrelated paths.

Apply consumer synchronization to "rb" and producer locking to "wb" and
"ab". Keep update modes containing '+' on the existing direct-to-libc,
unsupported path.

Update the reader-lock regression to verify that intercepted fopen("rb")
retains its shared OFD lock until fclose().
@JaeseungYeom
JaeseungYeom requested a review from wangvsa October 19, 2026 04:05
@wangvsa

wangvsa commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

Thanks!

@wangvsa
wangvsa merged commit e3471d6 into main Oct 19, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants