All files / src/h5 readTable.ts

77.59% Statements 239/308
54.54% Branches 48/88
100% Functions 17/17
77.59% Lines 239/308

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477                                          2x   2x   2x                             2x 9524x 9524x 9062x 791x                         2x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x 1087x                 2x 1090x 1090x 397888x 397888x 397888x 397888x 397888x 1090x 1090x                     2x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 1094x 1087x 1087x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x       7x 7x 7x 7x 7x     7x 7x 7x 1094x                     8430x 8430x 8430x 8430x 7639x 2753x     791x 791x   791x                                   8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x 8430x   8430x 8430x 8430x 8430x 8430x     7030x 7030x 7030x 791x 7030x 7030x 3486x 7030x 2753x 2753x 2753x 2753x       2753x 2753x 2753x 7030x 7030x     1400x 1400x 1400x   1400x 1400x 1400x 1400x                       1400x 1400x                     2x 7030x 7030x 7030x 7030x 7030x 7030x 7030x 7030x 7030x 7030x 7030x               7030x 7030x                                                 2x 1400x 1400x 1400x 1400x 1400x 1400x 1400x 1400x 1400x 1400x 1400x     1400x 1400x                                     2x 1333x 1333x 1333x 1333x 1333x 2429x 2429x 2429x 2429x 2429x   2429x 1333x 1977x 1977x     1977x 1977x 1977x   1977x 1333x 54x 54x     54x 54x     54x 54x 1333x 1333x                           2x 1091x 1091x 1091x 1091x 1091x 1091x 1091x 1091x 1091x 1091x 6164x 6164x 6164x 6164x 6164x 6164x 6164x   1091x 1091x                           1091x 1091x 1091x             1091x 1091x 1091x 1091x 6164x 3630x 6164x 1094x 1094x 1094x 6164x 2536x 2536x 2536x 6164x   6164x 6164x 1091x 1091x   2182x 2182x 2182x   9524x 9524x           9524x 9524x         9524x 9524x  
/**
 * Dataset decoding — the only code that touches raw HDF5 bytes.
 *
 * Two decisions here are load-bearing and both come from spec §6.2.
 *
 * **Strings are decoded from raw bytes, not from h5wasm's `slice()`.**
 * metacooler writes name columns as fixed-length `S<n>` sized by the *UTF-8
 * encoded byte length* (`_str_to_hdf5`), precisely so multi-byte characters
 * survive. h5py stamps those datatypes with the ASCII character set, and
 * h5wasm honours that literally: its `process_data` decodes them with
 * `TextDecoder('ascii')`, which is an alias for windows-1252, so `café` comes
 * back as `café`. Every byte is still there — only the decoding is wrong — so
 * this module reads the bytes itself and runs them through
 * `TextDecoder('utf-8')`, matching `schema.read_table`'s
 * `np.char.decode(data, "utf-8")` exactly.
 *
 * **Numbers are narrowed to `Float64Array` on read.** int64 columns arrive as
 * `BigInt64Array`, and BigInt does not mix with Number at runtime.
 */
 
import type { Column, Table } from '../types'
import { MetaCoolerFormatError } from '../errors'
import type { H5Module, H5wasmDataset, H5wasmFile, H5wasmGroup, Metadata } from './bootstrap'
import { lowWords, toNumberArray } from './typed'
 
const UTF8 = new TextDecoder('utf-8')
 
/** The HDF5 datatype classes this reader knows how to decode. */
export type H5Class = 'string' | 'number' | 'other'
 
/**
 * Classify a dataset by its HDF5 datatype *class* rather than by its dtype
 * string.
 *
 * Enumerations are the reason: h5py stores a pandas `bool` column as an HDF5
 * enum, and h5wasm's `metadata_to_dtype` has no enum branch, so its dtype
 * string is the literal `'unknown'`. Reading such a column as its base integer
 * is both possible and correct, and an optional metadata column must never be
 * able to make a whole table unreadable (spec §5.1).
 */
export function classify(h5: H5Module, md: Metadata): H5Class {
  const cls = h5.Module.H5T_class_t
  if (md.type === cls.H5T_STRING.value) return 'string'
  if (md.type === cls.H5T_INTEGER.value) return 'number'
  if (md.type === cls.H5T_FLOAT.value) return 'number'
  if (md.type === cls.H5T_ENUM.value) return 'number'
  return 'other'
}
 
/**
 * Copy a half-open row range of a 1-D dataset out of the wasm heap, undecoded.
 *
 * Mirrors `Dataset.slice()` but stops before `process_data`, which is where
 * h5wasm's ASCII string decode happens. The returned array is a copy: the wasm
 * heap can be detached by a later allocation, so a view would be a use-after-free
 * waiting to happen.
 */
export function readRawBytes(
  h5: H5Module,
  file: H5wasmFile,
  ds: H5wasmDataset,
  lo: number,
  hi: number,
): Uint8Array {
  const n = hi - lo
  if (n <= 0) return new Uint8Array(0)
  const md = ds.metadata
  const nbytes = md.size * n
  const ptr = malloc(h5, nbytes)
  try {
    h5.Module.get_dataset_data(
      file.file_id,
      ds.path,
      [BigInt(n)],
      [BigInt(lo)],
      [1n],
      BigInt(ptr),
    )
    return h5.Module.HEAPU8.slice(ptr, ptr + nbytes)
  } finally {
    h5.Module._free(ptr)
  }
}
 
/**
 * Split a fixed-length string buffer into UTF-8 decoded strings.
 *
 * Each record occupies exactly `itemSize` bytes and is NUL-padded on the
 * right. Truncating at the first NUL is what numpy does for an `S` dtype, so
 * the result matches the Python reader byte for byte.
 */
export function decodeFixedStrings(bytes: Uint8Array, itemSize: number, count: number): string[] {
  const out: string[] = new Array<string>(count)
  for (let i = 0; i < count; i++) {
    let item = bytes.subarray(i * itemSize, (i + 1) * itemSize)
    const nul = item.indexOf(0)
    if (nul > -1) item = item.subarray(0, nul)
    out[i] = UTF8.decode(item)
  }
  return out
}
 
/**
 * Read a half-open row range of a string dataset.
 *
 * Handles both storage forms `CORE_COLUMN_KINDS` permits: fixed-length `S<n>`
 * (kind `S`, what `metacooler create` writes) and variable-length strings
 * (kind `O`, what a file routed through `create cool` may carry). Vlen data is
 * a heap of pointers, so the borrowed strings are materialised before the
 * dataspace is reclaimed.
 */
export function readStringSlice(
  h5: H5Module,
  file: H5wasmFile,
  ds: H5wasmDataset,
  lo: number,
  hi: number,
): string[] {
  const n = hi - lo
  if (n <= 0) return []
  const md = ds.metadata
  if (!md.vlen) {
    return decodeFixedStrings(readRawBytes(h5, file, ds, lo, hi), md.size, n)
  }
 
  const nbytes = md.size * n
  const ptr = malloc(h5, nbytes)
  try {
    h5.Module.get_dataset_data(
      file.file_id,
      ds.path,
      [BigInt(n)],
      [BigInt(lo)],
      [1n],
      BigInt(ptr),
    )
    // Each element is a pointer into the wasm heap; decode with UTF8ToString
    // regardless of the datatype's declared character set, for the same reason
    // fixed-length columns are decoded as UTF-8 above.
    const pointers = new Uint32Array(h5.Module.HEAPU8.slice(ptr, ptr + nbytes).buffer)
    const out: string[] = new Array<string>(n)
    for (let i = 0; i < n; i++) out[i] = h5.Module.UTF8ToString(pointers[i])
    return out
  } finally {
    // Count-sized reclaim: the hyperslab read filled only `n` hvl_t structs, so
    // reclaiming the dataset's full extent would free past the buffer end.
    h5.Module.reclaim_vlen_memory_count(file.file_id, ds.path, '', BigInt(ptr), [BigInt(n)])
    h5.Module._free(ptr)
  }
}
 
/** Where a numeric slice can be read straight out of the wasm heap from. */
export interface HeapAccess {
  h5: H5Module
  file: H5wasmFile
}
 
/** The numeric layouts {@link heapSlice} reads directly: little-endian, four or eight bytes. */
type HeapKind = 'i64' | 'u64' | 'i32' | 'u32' | 'f64' | 'f32'
 
function heapKind(h5: H5Module, md: Metadata): HeapKind | null {
  if (md.littleEndian === false || md.vlen) return null
  const cls = h5.Module.H5T_class_t
  if (md.type === cls.H5T_INTEGER.value) {
    if (md.size === 8) return md.signed ? 'i64' : 'u64'
    if (md.size === 4) return md.signed ? 'i32' : 'u32'
    return null
  }
  if (md.type === cls.H5T_FLOAT.value) {
    if (md.size === 8) return 'f64'
    if (md.size === 4) return 'f32'
  }
  return null
}
 
/**
 * `[lo, hi)` of a 1-D numeric dataset, read into the wasm heap and narrowed
 * from there by `narrow`, or `null` where it is not one of the layouts this
 * reads (every other goes through h5wasm's own `slice()`).
 *
 * What `Dataset.slice()` does, short of its last step: the same hyperslab
 * through `get_dataset_data`, but where `slice()` then copies the bytes out
 * into a fresh array of the stored type — a `BigInt64Array` for an int64
 * column — the narrowing here reads them in place, so a window of a pixel
 * column is copied once, into the array handed back, and not twice. On a scan
 * of a whole table that was a few gigabytes of garbage. The values are the
 * ones `slice()` would have produced: the same bytes, through views of the type
 * h5wasm itself would have chosen for them.
 */
function heapSlice<T>(
  access: HeapAccess,
  ds: H5wasmDataset,
  lo: number,
  hi: number,
  narrow: (heap: ArrayBuffer, at: number, n: number, kind: HeapKind) => T,
): T | null {
  const md = ds.metadata
  const kind = heapKind(access.h5, md)
  if (kind === null) return null
  const n = hi - lo
  const { Module } = access.h5
  const ptr = malloc(access.h5, md.size * n)
  try {
    Module.get_dataset_data(access.file.file_id, ds.path, [BigInt(n)], [BigInt(lo)], [1n], BigInt(ptr))
    // The heap's buffer as it is *after* the read, which may have grown it.
    return narrow(Module.HEAPU8.buffer as ArrayBuffer, ptr, n, kind)
  } finally {
    Module._free(ptr)
  }
}
 
/** A heap slice as `Float64Array`: what {@link readNumericSlice} returns for it. */
function heapToFloat64(heap: ArrayBuffer, at: number, n: number, kind: HeapKind): Float64Array {
  switch (kind) {
    case 'f64':
      return new Float64Array(heap, at, n).slice()
    case 'i64':
    case 'u64':
      return toNumberArray(kind === 'i64' ? new BigInt64Array(heap, at, n) : new BigUint64Array(heap, at, n))
    default: {
      const out = new Float64Array(n)
      out.set(
        kind === 'i32'
          ? new Int32Array(heap, at, n)
          : kind === 'u32'
            ? new Uint32Array(heap, at, n)
            : new Float32Array(heap, at, n),
      )
      return out
    }
  }
}
 
/** A heap slice as `Int32Array`: what {@link readInt32Slice} returns for it. */
function heapToInt32(heap: ArrayBuffer, at: number, n: number, kind: HeapKind): Int32Array {
  switch (kind) {
    case 'i32':
      return new Int32Array(heap, at, n).slice()
    case 'i64':
    case 'u64':
      return lowWords(kind === 'i64' ? new BigInt64Array(heap, at, n) : new BigUint64Array(heap, at, n))
    default: {
      // `set` on an integer target applies ToInt32, as the slice path does.
      const out = new Int32Array(n)
      out.set(
        kind === 'u32'
          ? new Uint32Array(heap, at, n)
          : kind === 'f64'
            ? new Float64Array(heap, at, n)
            : new Float32Array(heap, at, n),
      )
      return out
    }
  }
}
 
/**
 * Read a half-open row range of a numeric dataset, narrowed to `Float64Array`.
 *
 * Enum datasets (h5py booleans) are read through their base integer type, so
 * `false`/`true` arrive as `0`/`1`.
 *
 * With `access`, a little-endian integer or float column is read straight out
 * of the wasm heap ({@link heapSlice}); the values are the same either way.
 */
export function readNumericSlice(
  ds: H5wasmDataset,
  lo: number,
  hi: number,
  access?: HeapAccess,
): Float64Array {
  const n = hi - lo
  if (n <= 0) return new Float64Array(0)
  if (access !== undefined) {
    const direct = heapSlice(access, ds, lo, hi, heapToFloat64)
    if (direct !== null) return direct
  }
  const raw = ds.slice([[lo, hi]])
  // Already the target type, and already a buffer h5wasm minted for this call
  // and will not touch again — so it is ours to hand on. Copying it into an
  // identical array was 8 B per element of pure duplication, and both copies
  // were live while it happened: on a float-count file that is the single
  // largest avoidable allocation in the read path.
  if (raw instanceof Float64Array) return raw
  if (raw instanceof BigInt64Array || raw instanceof BigUint64Array) return toNumberArray(raw)
  if (ArrayBuffer.isView(raw) && !(raw instanceof DataView)) {
    return toNumberArray(raw as unknown as ArrayLike<number>)
  }
  throw new MetaCoolerFormatError(
    `/${ds.path.replace(/^\//, '')} did not read back as a numeric array`,
    { path: ds.path },
  )
}
 
/**
 * Read a half-open row range of an integer column straight into `Int32Array`.
 *
 * For `pixels/bin1_id` and `pixels/bin2_id` — int64 on disk, and consumed as
 * array indices. {@link readNumericSlice} would widen them to `Float64Array`
 * and the caller would then narrow that to `Int32Array`, so a bin id passed
 * through three buffers of 8, 8 and 4 bytes to arrive somewhere 4 bytes wide.
 * This is the same single pass over the BigInt64 data, writing the final width
 * directly: 8 B per pixel of live memory that no longer exists, per column.
 *
 * Bin ids are bounded by the file's bin count, which every guard here keeps far
 * below 2^31, so the narrowing is exact — and it is made word by word
 * (`lowWords`), never through a BigInt per element, which was a third of what
 * reading the column cost. With `access`, straight out of the wasm heap
 * ({@link heapSlice}).
 */
export function readInt32Slice(
  ds: H5wasmDataset,
  lo: number,
  hi: number,
  access?: HeapAccess,
): Int32Array {
  const n = hi - lo
  if (n <= 0) return new Int32Array(0)
  if (access !== undefined) {
    const direct = heapSlice(access, ds, lo, hi, heapToInt32)
    if (direct !== null) return direct
  }
  const raw = ds.slice([[lo, hi]])
  if (raw instanceof Int32Array) return raw
  if (raw instanceof BigInt64Array || raw instanceof BigUint64Array) return lowWords(raw)
  if (ArrayBuffer.isView(raw) && !(raw instanceof DataView)) {
    const out = new Int32Array(n)
    // `set` on an integer target applies ToInt32, which is exact for the
    // integral values an index column holds.
    out.set(raw as unknown as ArrayLike<number>)
    return out
  }
  throw new MetaCoolerFormatError(
    `/${ds.path.replace(/^\//, '')} did not read back as a numeric array`,
    { path: ds.path },
  )
}
 
/**
 * Assemble a {@link Table} from already-decoded columns.
 *
 * Exported so the synthetic `/genomes` table a plain cooler needs (spec §9)
 * can be built without inventing a second Table shape.
 */
export function makeTable(length: number, columns: string[], data: Record<string, Column>): Table {
  return {
    length,
    columns,
    data,
    get(column: string, row: number): string | number | undefined {
      const col = data[column]
      if (col === undefined || row < 0 || row >= length) return undefined
      const value = (col as ArrayLike<unknown>)[row]
      if (typeof value === 'bigint') return Number(value)
      if (typeof value === 'string' || typeof value === 'number') return value
      return undefined
    },
    strings(column: string): string[] {
      const col = data[column]
      if (col === undefined) {
        throw new MetaCoolerFormatError(`no such column: ${column}`, { column })
      }
      if (Array.isArray(col) && (col.length === 0 || typeof col[0] === 'string')) {
        return col as string[]
      }
      throw new MetaCoolerFormatError(`column ${column} is not a string column`, { column })
    },
    numbers(column: string): number[] {
      const col = data[column]
      if (col === undefined) {
        throw new MetaCoolerFormatError(`no such column: ${column}`, { column })
      }
      if (col instanceof BigInt64Array) return Array.from(col, Number)
      if (Array.isArray(col) && col.length > 0 && typeof col[0] === 'string') {
        throw new MetaCoolerFormatError(`column ${column} is not a numeric column`, { column })
      }
      return Array.from(col as ArrayLike<number>)
    },
  }
}
 
/**
 * Read every column of a table group into a {@link Table}.
 *
 * The column *set* is discovered from the group and kept in file order, never
 * hard-coded, so the optional `/genomes` metadata columns a creator joined in
 * — completeness, contamination, taxonomy, anything — flow through to the UI
 * untouched (spec §5.1).
 *
 * A column whose datatype is neither numeric nor text (a compound, a reference)
 * is skipped rather than fatal: it can only ever be optional metadata, and a
 * file must not become unopenable because one extra column is exotic.
 */
export function readTableGroup(
  h5: H5Module,
  file: H5wasmFile,
  group: H5wasmGroup,
  label: string,
  lo?: number,
  hi?: number,
  columns?: readonly string[],
): Table {
  const datasets: { name: string; ds: H5wasmDataset; md: Metadata; length: number }[] = []
  for (const name of group.keys()) {
    const entity = group.get(name)
    if (!(entity instanceof h5.Dataset)) continue
    const md = entity.metadata
    const shape = md.shape
    if (!shape || shape.length !== 1) continue
    datasets.push({ name, ds: entity, md, length: shape[0] })
  }
 
  const lengths = new Set(datasets.map((d) => d.length))
  if (lengths.size > 1) {
    // Same failure and the same wording as `schema._table_length`: a truncated
    // column silently mis-pairs values with records.
    const detail = datasets
      .map((d) => `${d.name}=${d.length}`)
      .sort()
      .join(', ')
    throw new MetaCoolerFormatError(
      `/${label} columns have unequal lengths (${detail}); every column of a table ` +
        'must have one row per record',
      { table: label },
    )
  }
 
  const total = datasets.length === 0 ? 0 : datasets[0].length
  const start = clamp(lo ?? 0, 0, total)
  const stop = clamp(hi ?? total, start, total)
 
  // The *lengths* above are metadata and cost no read, so the equal-length
  // check runs over the whole group whatever is asked for. Only the decode
  // below is narrowed — a column the caller did not ask for is simply absent
  // from the result, which is exactly how a column that is not in the file
  // reads, so a required-column check still fires for a file that lacks one.
  const wanted = columns === undefined ? null : new Set(columns)
  const names: string[] = []
  const data: Record<string, Column> = {}
  for (const { name, ds, md } of datasets) {
    if (wanted !== null && !wanted.has(name)) continue
    switch (classify(h5, md)) {
      case 'string':
        names.push(name)
        data[name] = readStringSlice(h5, file, ds, start, stop)
        break
      case 'number':
        names.push(name)
        data[name] = readNumericSlice(ds, start, stop, { h5, file })
        break
      case 'other':
        break
    }
  }
  return makeTable(stop - start, names, data)
}
 
function clamp(value: number, lo: number, hi: number): number {
  return Math.min(Math.max(Math.trunc(value), lo), hi)
}
 
function malloc(h5: H5Module, nbytes: number): number {
  if (nbytes > h5.Module.MAXIMUM_MEMORY) {
    throw new MetaCoolerFormatError(
      `a ${nbytes} byte read exceeds the wasm heap limit of ${h5.Module.MAXIMUM_MEMORY} bytes`,
      { nbytes, limit: h5.Module.MAXIMUM_MEMORY },
    )
  }
  const ptr = h5.Module._malloc(nbytes)
  if (ptr === 0) {
    throw new MetaCoolerFormatError(`allocation of ${nbytes} bytes in the wasm heap failed`, {
      nbytes,
    })
  }
  return ptr
}