|
NEP 4.3.0
NetCDF Expansion Pack
|
This page explains how the nxCDF backend works internally. It is written for readers who know netCDF at the nc_open()/nc_put_var() level but have not looked inside a format backend. The user-facing guide is nxCDF Backend.
netcdf-c lets third-party libraries register additional on-disk formats through User Defined Format (UDF) dispatch tables. The released NetCDF-C 4.10.1 provides 10 UDF slots (UDF0–UDF9), and the pinned development revision provides 64 (UDF0–UDF63). nxCDF supports both without patching NetCDF-C; each slot holds one format identifier and one dispatch table. NEP registers nxCDF in slot 9: the public constant NC_NXCDF is NEP_UDF_NXCDF, which is NC_UDF9 (see include/nep.h and include/nxcdf/nxcdf.h).
Registration happens once per process:
nxCDF does not claim the HDF5 magic bytes — those belong to netcdf-c's built-in NetCDF-4 backend. Files must be created and opened explicitly with NC_NXCDF in the mode flags. A .ncrc autoload entry (NETCDF.UDF9.LIBRARY/NETCDF.UDF9.INIT) can spare the application the NC_NXCDF_initialize() call, but the mode flag is still required.
Every netCDF API call (nc_open, nc_def_dim, nc_put_vara, ...) is routed through a table of function pointers, NC_Dispatch, one per open file. NXCDF_dispatcher in src/nxcdf/nxcdf_dispatch.c fills that table three ways:
The struct has no designated initializers, so table entries appear in exact positional order.
On released 10-slot headers, NXCDF_DISPATCH_MODEL sets the table's private model field to NC_FORMATX_NC_HDF5: upstream's USEFILEINFO classification recognizes HDF5's shared NC_FILE_INFO_T metadata, but not UDF9. This allows public and internal recursive copy/reclaim and metadata teardown to use the correct type tree without changing the dependency. On 64-slot headers the table model remains NC_FORMATX_NXCDF. Registration and selection remain UDF9 in both schemes, and NXCDF_inq_format_extended always reports the public NC_FORMATX_NXCDF, not the legacy private model. No HDF5 magic bytes or built-in dispatch entry is replaced. The existing extended-atomic cleanup still runs: classifying metadata does not teach upstream about nxCDF-only atomic types. tst_nxcdf_udf_compat covers public format inquiry, simultaneous built-in/nxCDF files, subgroup-owned recursive types and public copy/reclaim across reopen; normal and sanitizer CI run against both dependency revisions.
netcdf-c keeps one in-memory metadata tree per open file, built from NC_FILE_INFO_T, NC_GRP_INFO_T, NC_DIM_INFO_T, NC_VAR_INFO_T, NC_ATT_INFO_T and NC_TYPE_INFO_T. Each of these structs has a format_*_info field where a backend hangs its private state. nxCDF's private structs are declared in src/nxcdf/nxcdf_internal.h:
| Struct | Hangs off | Holds |
|---|---|---|
| NXCDF_FILE_INFO_T | NC_FILE_INFO_T | hdfid (the HDF5 file), rootid, path, mode, no_write, define_mode, netcdf4_model, backend_marked, created_by_us, ncproperties |
| NXCDF_GRP_INFO_T | NC_GRP_INFO_T | open hid_t for the HDF5 group |
| NXCDF_DIM_INFO_T | NC_DIM_INFO_T | hid_t of the dimension-scale dataset |
| NXCDF_VAR_INFO_T | NC_VAR_INFO_T | hid_t of the variable dataset plus flags (e.g. NC_HDF5_VAR_FILTER_MISSING); the filter pipeline itself lives on the shared NC_VAR_INFO_T::filters list |
| NXCDF_TYPE_INFO_T | NC_TYPE_INFO_T | committed HDF5 datatype hid_t |
NXCDF_add_file/NXCDF_get_file/NXCDF_free_file in nxcdf_file.c manage the file-level record. The rule throughout: whoever opens an HDF5 object closes it; H5Tcopy results are owned by the caller.
nxCDF stores bookkeeping as ordinary HDF5 attributes that must be hidden from nc_inq_att* results. The names are macros in nxcdf_internal.h, and is_reserved_att() in nxcdf_meta.c filters them out:
| Macro | Attribute | Written on |
|---|---|---|
| NXCDF_BACKEND_ATT | _NxcdfBackend = "nxCDF/1.0" | root group |
| NXCDF_MODEL_ATT | _NxcdfModel | root group (NC_NETCDF4_MODEL only) |
| NXCDF_DIMID_ATT | _Netcdf4Dimid | dimension scale |
| NXCDF_VARID_ATT | _NxcdfVarid | variable dataset |
| NXCDF_VARDIMIDS_ATT | _Netcdf4Coordinates | variable dataset |
| NXCDF_DIMCLASS | CLASS = "DIMENSION_SCALE" | dimension scale |
Dimensions are stored as HDF5 dimension scales — datasets marked with CLASS = "DIMENSION_SCALE" and attached to the variable datasets that use them. _Netcdf4Coordinates records a variable's dimids so open can map ids fast; dimension-scale matching is the fallback for files written without it.
nxcdf_provenance.c reproduces upstream's provenance surface so third-party tools cannot tell a nxCDF file from an upstream NetCDF-4 file:
A nxCDF file is in define mode while dimensions, variables, attributes and types are being defined, and in data mode while data is read or written. nc_enddef/nc_redef switch between them through NXCDF__enddef/NXCDF_redef in nxcdf_file.c.
Type ids at or above NC_FIRSTUSERTYPEID (32) are user-defined types; lower ids are atomic or NEP extended types. nxcdf_type.c provides the context-aware plumbing that every consumer routes through:
Committed datatypes are written at _enddef (NXCDF_write_types); variables defined over a not-yet-committed type defer dataset creation until then, and attributes over them queue similarly. At open, each group's committed datatypes are loaded before variables and attributes (load_types/load_one_type in nxcdf_meta.c), so a dataset or attribute whose datatype is a shared committed type resolves it back to the registered NC_TYPE_INFO_T by object token (nxcdf_hdf_type_match, with an H5Tequal structural fallback for anonymously stored types).
User-type I/O is matching-type or untyped only: var_io rejects a typed request for a different memtype with NC_EBADTYPE and never routes user types through nxcdf_convert_type. The memory datatype is rebuilt field-by-field for compounds (native-endian members at the recorded offsets), as H5Tenum_create over the integer base for enums, and as a plain H5T_OPAQUE for opaque types, so HDF5 handles byte-order conversion while the element layout the caller sees is the type's exact nc_inq_* layout.
Vlen types (NXCDF_def_vlen) wrap H5Tvlen_create over any atomic or user-defined base, including strings and other vlens; the type graph rejects NC_STD_REF, unknown bases and cycles, and commits bases before dependents via commit_type_tree. NC_TYPE_INFO_T:: varsized is maintained recursively — a vlen is variable-sized, and a compound is variable-sized when any field (including fields of array fields) is — so I/O, attribute and fill paths can tell flat from dynamic values. String leaves make a compound dynamic; NC_CHAR is not pointer-bearing even though its synthetic metadata class is NC_STRING. Sprint 1P's nxcdf_copy_data recursively initializes copies and unwinds partial failures, including nested strings. nxcdf_storage_memory_type preserves stored string character-set tags while retaining native memory sizes, member offsets and array shapes. String fill caches hold an owned pointer-sized element buffer, never a bare character buffer. Recognized attribute-load failures propagate instead of silently dropping data. Dynamic filled datasets allocate early so read-only missing-chunk reads do not attempt vlen-heap writes in HDF5 2.1.1; this increases sparse-file storage costs. Scalar datasets omit _Netcdf4Coordinates rather than writing an empty attribute that upstream cannot parse. Clipped unlimited reads select real values into their full logical memory positions and supply each missing element independently, including strided selections.
Elements are nc_vlen_t {size_t len; void *p} descriptors:
Read results (nc_get_var*, nc_get_att) are owned deep copies: HDF5's read buffer is handed to the caller and must be freed with nc_reclaim_data (recursive over nested vlens and dynamic compound fields; does not free the top-level buffer) or nc_reclaim_data_all (frees it too). The legacy nc_free_vlen/nc_free_vlens/ nc_free_string helpers are flat-only. Reclaim must happen before nc_close — NC_reclaim_data needs valid file and type context, and both supported UDF schemes resolve the correct metadata tree, using the private dispatch-model adaptation described above on 10-slot headers. On a failed variable read any HDF5-allocated payloads are reclaimed recursively before the error is returned.
Attribute and fill-value metadata that lives in memory is stored deep-copied (nc_copy_data into caller-independent storage for dynamic types), so a nc_put_att caller may free or reuse its payload immediately and every nc_get_att returns a fresh independent copy. netcdf-c's nc4_rec_grp_del_att_data/var_free paths reclaim this owned storage at nc_close. _FillValue for variable-sized types takes the same deep-copy path both when written as an attribute and when mirrored into var->fill_value.
NXCDF_set_fill updates shared NC_FILE_INFO_T.fill_mode without entering define mode or rewriting existing datasets. Definitions capture the default before eager creation; user-defined, string and reference fill rules are preserved. Opens start at NC_FILL. Per-variable fill overrides remain DCPL setters, distinct from this session default.
nxcdf_var_dapl maps netCDF bytes/slots/float-preemption to HDF5 slots/bytes/double-preemption. Dataset creation and deferred rebuild use it; loaded variable handles are reopened with global NetCDF defaults. nxcdf_reopen_var_cache finds owned variable/scale aliases by object token, allocates its path/property lists before mutation, flushes writable files, closes all aliases, then reopens with the requested DAPL. On failure it attempts to restore the old access properties; no datasets or dimension attachments are recreated. Getters query live chunked DAPLs; pending/nonchunked variables retain their requests. Existing full-suite normal and sanitizer CI covers the nxcdf_controls focused tests.
NXCDF_rename_grp validates normalized names and parent variable/group/type collisions, moves the HDF5 link, updates the parent child index and flushes. Open descendant IDs and object identities remain valid, and full-name inquiry derives new paths from the metadata tree. Native and NetCDF-4-model groups are supported; classic mode remains root-only. See nxCDF Renames for the full rename semantics and the cases still open. Unsupported memory, sharing and parallel flags are rejected by NXCDF_check_mode before filesystem side effects; image files remain deferred. Native serial SWMR writers use NC_SWMR_WRITE or nc_start_swmr_write; readers open with NC_SWMR_READ and call nc_swmr_refresh. Optional MPI-IO sessions use the Sprint 1V1 file plumbing and Sprint 1V2 per-variable access described below.
NXCDF_FILE_INFO_T.swmr_requested records deferred activation and swmr_active records successful H5Fstart_swmr_write. Flagged creates activate only after enddef materializes the schema; flagged writable opens activate after metadata load. Explicit nc_start_swmr_write preflights and commits definitions, then uses the same activation helper. nxcdf_swmr_validate checks native serial state, actual superblock v3, SWMR VFD capability and the complete schema tree: no declared user types or string/reference/user-defined variables. Open attributes and committed datatypes cannot survive HDF5 activation; the restricted schema avoids adding a committed-type handle lifecycle. An inactive requested session closes as an ordinary file, never activating solely to close.
Active sessions cannot re-enter define mode or mutate schema/attributes. The common write-define guard and direct type/group/reference mutator guards return NC_EPERM; committed dataset setters return NC_ELATEDEF. Variable data I/O and cache-alias reopen remain available without creating objects. Provenance is materialized before activation and is not rewritten by active sync/close. nxcdf_swmr_flush walks variable datasets, then dimension scales, then calls H5Fflush; alias handles stay owned and may safely be flushed twice. Public nc_swmr_flush, active nc_sync and close share this path. No writer refresh, record transaction or physical durability guarantee is introduced. See nxCDF for the public writer contract.
NXCDF_FILE_INFO_T.swmr_read records a session opened read-only with NC_NXCDF | NC_SWMR_READ: the open selects H5F_ACC_RDONLY | H5F_ACC_SWMR_READ, loads markers and metadata normally, then requires the actual superblock to be v3 (NC_NETCDF4_MODEL files qualify when they carry one). Write/compat/classic/MPI combinations are rejected, as is the flag at create.
nc_swmr_refresh runs nxcdf_swmr_refresh, which H5Drefreshes every variable dataset then every dimension-scale dataset, reloading each scale's current extent into the cached dim->len that nc_inq_dimlen reports. Read paths already reacquire dataspaces per call, so refreshed handles return current data. One measured HDF5 constraint drives nxcdf_swmr_read_aliases: two open handles to the same object defeat SWMR visibility (reads stay at the open-time snapshot even after H5Drefresh), so each coordinate variable's scale/variable handle pair is collapsed at open — and idempotently inside refresh — to the variable's own handle; the duplicate close is safe because nxcdf_close_group_hdf tolerates a twice-closed identifier. Refresh is not a re-open: no new metadata is discovered, matching the writer's frozen-schema contract. Readers and writers may close in either order; multiple simultaneous readers are covered by tst_nxcdf_swmr under nxcdf_swmr.
NXCDF_var_par_access records an independent/collective preference in NXCDF_VAR_INFO_T.parallel_access, not in file metadata. It is initialized independent at definition/open and preserved by dataset rebuilds and cache-handle reopens. Filter setters force collective in parallel sessions; independent filtered access is rejected. Reopened filtered variables require explicit collective selection.
var_io owns a per-call DXPL configured by H5Pset_dxpl_mpio, closes it on every exit, and keeps serial transfers unchanged. Empty or fill-only collective ranks use none-selected memory/file spaces rather than skipping HDF5. Collective unlimited writes reduce proposed extents with MPI_MAX over the file's owned communicator, extend the variable and dimension scales consistently and preserve longer shared dimensions. Independent extension returns NC_ECANTEXTEND before mutation.
Fixed-size standard/user types and NEP small floats use the existing native-memory conversion engine; parallel dynamic/string/reference variable transfers return NC_ENOTBUILT before automatic enddef or mutation. Completed conversion range warnings stay rank-local and do not skip a collective call. The API requires valid arguments and matching collective order rather than providing a general rank-local failure-consensus layer. HDF5 may fall back internally from requested collective I/O; no physical MPI algorithm is guaranteed. Four-rank Open MPI tests cover the contract under nxcdf_parallel; no new build option or packaging requirement is introduced.
Variable filter pipelines are stored on NC_VAR_INFO_T::filters — an NClist of struct NC_HDF5_Filter — managed with netcdf-c's exported NC4_hdf5_* helpers (NC4_hdf5_addfilter, NC4_hdf5_filter_lookup, NC4_hdf5_filter_freelist), exactly as the built-in HDF5 backend does in libhdf5/hdf5filter.c. All filter code lives in nxcdf_filter.c:
NC_CLASSIC_MODEL files reject every filter and storage setter with NC_EINVAL; scalars reject filters; and committed variables reject every dataset-property setter — filters, chunking, fill, endianness, quantization — with NC_ELATEDEF, matching upstream's nc_def_var_extra.
| Mode flag | Superblock | Data model |
|---|---|---|
| (none) | v3 | full nxCDF, all extended types |
| NC_CLASSIC_MODEL | v3 | NetCDF-3 model only: root group, one unlimited dim, classic atomic types |
| NC_NETCDF4_MODEL | v1 | enhanced model, no nxCDF-only types; file readable by upstream netcdf-c on HDF5 1.10+ |
The flags are mutually exclusive. NXCDF_check_atomic_type() enforces the per-mode type restrictions at nc_def_var time.
Functions use a ret variable plus a fail: cleanup label (nxcdf_err.h):
ELOG((level, fmt, ...)) writes to stderr at levels 0 (errors) to 3 (metadata ops), controlled by NEP_LOG_LEVEL or nep_set_log_level(); -DNEP_ENABLE_LOGGING=OFF compiles it out.
nxcdf_convert.c contains NEP's own numeric conversion engine nxcdf_convert_type(), used for variable, attribute and quantized-write conversions. It reports overflow and integer range errors as NC_ERANGE after completing the I/O — the data still lands — and treats precision loss and fractional truncation as non-errors. IEEE float16 joined the engine in Sprint 1J (v4.3.0); the only remaining exclusion is the raw-bit small-float types (FP8/FP6/FP4) which are untyped-only. The nc_*_bfloat16 and nc_*_float16 families perform NEP round-to-nearest-even conversion between NC_BFLOAT16/NC_FLOAT16 storage and NC_FLOAT/NC_DOUBLE buffers.