qvdjs 0.9.4 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import crypto from 'crypto';
4
4
  import xml2 from 'xml2js';
5
- import assert from 'assert';
5
+ import assert2 from 'assert';
6
6
  import os from 'os';
7
7
  import v8 from 'v8';
8
8
 
@@ -355,6 +355,55 @@ var init_validatePath = __esm({
355
355
  }
356
356
  });
357
357
 
358
+ // src/util/bitUtils.js
359
+ function fieldGeometry(bitOffset, bitWidth) {
360
+ const shift = bitOffset & 7;
361
+ return {
362
+ byteStart: bitOffset >>> 3,
363
+ shift,
364
+ byteCount: bitWidth === 0 ? 0 : shift + bitWidth + 7 >>> 3
365
+ };
366
+ }
367
+ function decodeIndexColumn(buffer, recordSize, rowCount, bitOffset, bitWidth, bias, out) {
368
+ if (bitWidth === 0) {
369
+ out.fill(bias, 0, rowCount);
370
+ return out;
371
+ }
372
+ const { byteStart, shift, byteCount } = fieldGeometry(bitOffset, bitWidth);
373
+ const divisor = POW2[shift];
374
+ const modulus = POW2[bitWidth];
375
+ let base = byteStart;
376
+ for (let row = 0; row < rowCount; row++, base += recordSize) {
377
+ let acc = buffer[base];
378
+ if (byteCount > 1) acc += buffer[base + 1] * 256;
379
+ if (byteCount > 2) acc += buffer[base + 2] * 65536;
380
+ if (byteCount > 3) acc += buffer[base + 3] * 16777216;
381
+ if (byteCount > 4) acc += buffer[base + 4] * 4294967296;
382
+ out[row] = Math.floor(acc / divisor) % modulus + bias;
383
+ }
384
+ return out;
385
+ }
386
+ function writeBitField(buffer, recordBase, geometry, value) {
387
+ const { byteStart, shift, byteCount } = geometry;
388
+ if (byteCount === 0) {
389
+ return;
390
+ }
391
+ const base = recordBase + byteStart;
392
+ const shifted = value * POW2[shift];
393
+ buffer[base] |= shifted % 256;
394
+ if (byteCount > 1) buffer[base + 1] |= Math.floor(shifted / 256) % 256;
395
+ if (byteCount > 2) buffer[base + 2] |= Math.floor(shifted / 65536) % 256;
396
+ if (byteCount > 3) buffer[base + 3] |= Math.floor(shifted / 16777216) % 256;
397
+ if (byteCount > 4) buffer[base + 4] |= Math.floor(shifted / 4294967296) % 256;
398
+ }
399
+ var MAX_BIT_WIDTH, POW2;
400
+ var init_bitUtils = __esm({
401
+ "src/util/bitUtils.js"() {
402
+ MAX_BIT_WIDTH = 31;
403
+ POW2 = Array.from({ length: 41 }, (_, exponent) => 2 ** exponent);
404
+ }
405
+ });
406
+
358
407
  // src/QvdFileWriter.js
359
408
  var QvdFileWriter_exports = {};
360
409
  __export(QvdFileWriter_exports, {
@@ -364,7 +413,9 @@ var QvdFileWriter;
364
413
  var init_QvdFileWriter = __esm({
365
414
  "src/QvdFileWriter.js"() {
366
415
  init_QvdSymbol();
416
+ init_QvdErrors();
367
417
  init_validatePath();
418
+ init_bitUtils();
368
419
  QvdFileWriter = class _QvdFileWriter {
369
420
  /**
370
421
  * Constructs a new QVD file writer.
@@ -389,8 +440,9 @@ var init_QvdFileWriter = __esm({
389
440
  this._symbolTable = null;
390
441
  this._symbolTableMetadata = null;
391
442
  this._indexBuffer = null;
392
- this._indexTable = null;
443
+ this._symbolIndexByValue = null;
393
444
  this._indexTableMetadata = null;
445
+ this._recordCount = 0;
394
446
  this._recordByteSize = null;
395
447
  }
396
448
  /**
@@ -415,9 +467,9 @@ var init_QvdFileWriter = __esm({
415
467
  * Writes the data to the QVD file.
416
468
  */
417
469
  async _writeData() {
418
- assert(this._header, "The QVD file header has not been parsed.");
419
- assert(this._symbolBuffer, "The QVD file symbol table has not been parsed.");
420
- assert(this._indexBuffer, "The QVD file index table has not been parsed.");
470
+ assert2(this._header, "The QVD file header has not been parsed.");
471
+ assert2(this._symbolBuffer, "The QVD file symbol table has not been parsed.");
472
+ assert2(this._indexBuffer, "The QVD file index table has not been parsed.");
421
473
  this._emitProgress("write", 0, 1);
422
474
  const headerBuffer = Buffer.concat([Buffer.from(this._header, "utf-8"), Buffer.from([0])]);
423
475
  let fd;
@@ -512,7 +564,7 @@ var init_QvdFileWriter = __esm({
512
564
  };
513
565
  })
514
566
  },
515
- NoOfRecords: this._indexTable?.length,
567
+ NoOfRecords: this._recordCount,
516
568
  RecordByteSize: this._recordByteSize,
517
569
  Offset: this._symbolTableMetadata && this._symbolTableMetadata.length > 0 ? this._symbolTableMetadata[this._symbolTableMetadata.length - 1][0] + this._symbolTableMetadata[this._symbolTableMetadata.length - 1][1] : 0,
518
570
  Length: this._indexBuffer?.length
@@ -551,128 +603,133 @@ var init_QvdFileWriter = __esm({
551
603
  _buildSymbolTable() {
552
604
  this._symbolTable = [];
553
605
  this._symbolTableMetadata = [];
554
- this._symbolBuffer = Buffer.alloc(0);
555
- const numColumns = this._df.columns.length;
556
- this._emitProgress("symbol-table", 0, numColumns);
557
- const uniqueValuesSets = this._df.columns.map(() => /* @__PURE__ */ new Set());
558
- this._df.data.forEach((row) => {
559
- this._df.columns.forEach((column, columnIndex) => {
560
- const value = row[columnIndex];
561
- uniqueValuesSets[columnIndex].add(value);
606
+ this._symbolIndexByValue = [];
607
+ if (this._df.columns.length === 0) {
608
+ throw new QvdValidationError("A QVD file must have at least one field", {
609
+ file: this._path,
610
+ stage: "buildSymbolTable"
562
611
  });
563
- });
564
- this._df.columns.forEach((column, columnIndex) => {
565
- const uniqueValuesSet = uniqueValuesSets[columnIndex];
566
- const uniqueValues = Array.from(uniqueValuesSet);
567
- const containsNull = uniqueValues.includes(null) || uniqueValues.includes(void 0);
568
- const symbols = uniqueValues.filter((value) => value !== null && value !== void 0).map((value) => _QvdFileWriter._convertRawToSymbol(value));
569
- const currentSymbolBuffer = Buffer.concat(symbols.map((symbol) => symbol.toByteRepresentation()));
570
- this._symbolBuffer = this._symbolBuffer ? Buffer.concat([this._symbolBuffer, currentSymbolBuffer]) : currentSymbolBuffer;
571
- const symbolsLength = currentSymbolBuffer.length;
572
- const symbolsOffset = this._symbolBuffer.length - symbolsLength;
573
- this._symbolTableMetadata?.push([symbolsOffset, symbolsLength, containsNull]);
612
+ }
613
+ const columns = this._df.columns;
614
+ const data = this._df.data;
615
+ const numColumns = columns.length;
616
+ const numRows = data.length;
617
+ this._emitProgress("symbol-table", 0, numColumns);
618
+ const indexByValue = columns.map(() => /* @__PURE__ */ new Map());
619
+ const containsNull = columns.map(() => false);
620
+ for (let row = 0; row < numRows; row++) {
621
+ const values = data[row];
622
+ for (let column = 0; column < numColumns; column++) {
623
+ const value = values?.[column];
624
+ if (value === null || value === void 0) {
625
+ containsNull[column] = true;
626
+ continue;
627
+ }
628
+ const map = indexByValue[column];
629
+ if (!map.has(value)) {
630
+ map.set(value, map.size);
631
+ }
632
+ }
633
+ }
634
+ const columnBuffers = [];
635
+ let symbolsOffset = 0;
636
+ for (let column = 0; column < numColumns; column++) {
637
+ const symbols = Array.from(indexByValue[column].keys(), (value) => _QvdFileWriter._convertRawToSymbol(value));
638
+ const columnBuffer = Buffer.concat(symbols.map((symbol) => symbol.toByteRepresentation()));
639
+ columnBuffers.push(columnBuffer);
640
+ this._symbolTableMetadata?.push([symbolsOffset, columnBuffer.length, containsNull[column]]);
574
641
  this._symbolTable?.push(symbols);
575
- this._emitProgress("symbol-table", columnIndex + 1, numColumns);
576
- });
642
+ this._symbolIndexByValue.push(indexByValue[column]);
643
+ symbolsOffset += columnBuffer.length;
644
+ this._emitProgress("symbol-table", column + 1, numColumns);
645
+ }
646
+ this._symbolBuffer = Buffer.concat(columnBuffers);
577
647
  }
578
648
  /**
579
- * Builds the index table of the QVD file.
580
- *
581
- * PERFORMANCE OPTIMIZATION: Uses Map-based lookups for O(1) symbol index retrieval
582
- * instead of Array.findIndex() which is O(n). For columns with many unique values,
583
- * this provides significant performance improvements.
649
+ * Builds the bit-packed index table of the QVD file.
584
650
  *
585
- * Algorithm:
586
- * 1. Build Map<symbol, index> for each column (O(m) where m=unique values)
587
- * 2. For each data row, lookup indices in maps (O(1) per value)
588
- * 3. Convert indices to bit-packed binary format
651
+ * A record is `recordByteSize` bytes. Each column occupies `bitWidth` consecutive bits at
652
+ * `bitOffset`, least significant bit first, where bit `p` of a record is
653
+ * `(byte[p >> 3] >> (p & 7)) & 1`. `Bias` is -2 for a column containing NULLs: stored index 0
654
+ * means NULL, and real symbols start at 2. This is exactly what the reader's
655
+ * `decodeIndexColumn` undoes, and `writeBitField` is its inverse.
589
656
  *
590
- * Bit Packing:
591
- * - Calculates minimum bits needed: ceil(log2(numSymbols))
592
- * - Packs indices into binary string, then converts to bytes
593
- * - Reduces file size significantly for columns with few unique values
657
+ * The previous implementation went the long way round. Per cell it converted the raw value to
658
+ * a QvdSymbol - a second time, the symbol table pass having already done it - to build a
659
+ * template-literal lookup key, then turned the resulting index into a string of bits via
660
+ * `toString(2).split('').map().reverse().concat().slice().reverse()`. Per row it kept an array
661
+ * of those strings, padded each with `padStart`, reversed and joined them, split the result
662
+ * with `/.{1,8}/g`, and allocated a Buffer; then `Buffer.concat` over one Buffer per row. On
663
+ * the 1.7M-row taxi fixture that is 34 million symbols, 34 million key strings, 34 million bit
664
+ * strings and 1.7 million Buffers, and it accounted for 98% of a write.
594
665
  *
595
- * Example: Column with 10 unique values needs only 4 bits per value
596
- * instead of 32 bits (full integer), saving 87.5% space.
666
+ * Now: the widths are derived from the symbol counts, the offsets by prefix sum, one Buffer is
667
+ * allocated for the whole table, and each value is OR-ed into place as an integer.
597
668
  *
598
669
  * @private
599
670
  */
600
671
  _buildIndexTable() {
601
- this._indexTable = [];
672
+ assert2(this._symbolTable, "The QVD file symbol table has not been built.");
673
+ assert2(this._symbolTableMetadata, "The QVD file symbol table metadata has not been built.");
674
+ assert2(this._symbolIndexByValue, "The QVD file symbol index has not been built.");
602
675
  this._indexTableMetadata = [];
603
- this._indexBuffer = Buffer.alloc(0);
604
- const numRows = this._df.data.length;
676
+ const columns = this._df.columns;
677
+ const data = this._df.data;
678
+ const numRows = data.length;
679
+ const numColumns = columns.length;
680
+ this._recordCount = numRows;
605
681
  this._emitProgress("index-table", 0, numRows);
606
- const symbolIndexMaps = this._symbolTable?.map((symbols) => {
607
- const map = /* @__PURE__ */ new Map();
608
- symbols.forEach((symbol, idx) => {
609
- const key = `${symbol.intValue}|${symbol.doubleValue}|${symbol.stringValue}`;
610
- map.set(key, idx);
611
- });
612
- return map;
613
- });
614
- let processedRows = 0;
615
- const progressInterval = Math.max(1, Math.floor(numRows / 100));
616
- this._df.data.forEach((row) => {
617
- const indices = this._df.columns.map((column, columnIndex) => {
618
- const value = row[columnIndex];
619
- const symbol = _QvdFileWriter._convertRawToSymbol(value);
620
- const fieldContainsNull = this._symbolTableMetadata?.[columnIndex][2];
621
- if (symbol === null) {
622
- return 0;
623
- } else {
624
- const key = `${symbol.intValue}|${symbol.doubleValue}|${symbol.stringValue}`;
625
- const symbolIndex = symbolIndexMaps?.[columnIndex].get(key);
626
- return fieldContainsNull ? (symbolIndex ?? 0) + 2 : symbolIndex ?? 0;
682
+ const layout = [];
683
+ let totalBits = 0;
684
+ for (let column = 0; column < numColumns; column++) {
685
+ const fieldContainsNull = this._symbolTableMetadata[column][2];
686
+ const symbolCount = this._symbolTable[column].length;
687
+ const nullShift = fieldContainsNull ? 2 : 0;
688
+ const maxStoredIndex = symbolCount === 0 ? 0 : symbolCount - 1 + nullShift;
689
+ const bitWidth = maxStoredIndex === 0 ? 0 : 32 - Math.clz32(maxStoredIndex);
690
+ for (const index of this._symbolIndexByValue[column].values()) {
691
+ if (index + nullShift > maxStoredIndex) {
692
+ throw new QvdValidationError("The symbol table and the index table are out of sync", {
693
+ field: columns[column],
694
+ storedIndex: index + nullShift,
695
+ maxStoredIndex,
696
+ symbolCount,
697
+ file: this._path,
698
+ stage: "buildIndexTable"
699
+ });
627
700
  }
628
- });
629
- const stringIndices = indices.map((index) => {
630
- const bits = _QvdFileWriter._convertInt32ToBits(index, 32);
631
- let bitString = bits.join("");
632
- bitString = bitString.replace(/^0+/, "") || "0";
633
- return bitString;
634
- });
635
- this._indexTable?.push(stringIndices);
636
- processedRows++;
637
- if (processedRows % progressInterval === 0 || processedRows === numRows) {
638
- this._emitProgress("index-table", processedRows, numRows);
639
701
  }
640
- });
641
- this._df.columns.forEach((column, columnIndex) => {
642
- const bitOffset = this._indexTableMetadata?.slice(0, columnIndex).reduce((sum, metadata) => sum + metadata[1], 0);
643
- assert(this._indexTable, "The QVD file header has not been parsed.");
644
- const fieldContainsNull = this._symbolTableMetadata?.[columnIndex][2];
645
- const bias = fieldContainsNull ? -2 : 0;
646
- const symbolCount = this._symbolTable?.[columnIndex].length ?? 0;
647
- const maxStoredIndex = symbolCount === 0 ? 0 : symbolCount - 1 + (fieldContainsNull ? 2 : 0);
648
- const bitWidth = maxStoredIndex === 0 ? 0 : 32 - Math.clz32(maxStoredIndex);
649
- this._indexTableMetadata?.push([bitOffset, bitWidth, bias]);
650
- this._indexTable.forEach((indices) => {
651
- const bitString = indices[columnIndex];
652
- assert(
653
- bitString === "0" || bitString.length <= bitWidth,
654
- `Stored index for column '${column}' needs ${bitString.length} bits, but BitWidth was derived as ${bitWidth} from ${symbolCount} symbols. The symbol table and the index table are out of sync.`
655
- );
656
- indices[columnIndex] = bitWidth === 0 ? "" : bitString.padStart(bitWidth, "0");
657
- });
658
- });
659
- this._indexBuffer = Buffer.concat(
660
- // @ts-ignore - Buffer array type compatibility
661
- this._indexTable.map((indices) => {
662
- indices.reverse();
663
- const bits = indices.join("");
664
- if (bits.length === 0) {
665
- return Buffer.from(Uint8Array.from([0]));
702
+ layout.push({ geometry: fieldGeometry(totalBits, bitWidth), nullShift });
703
+ this._indexTableMetadata.push([totalBits, bitWidth, fieldContainsNull ? -2 : 0]);
704
+ totalBits += bitWidth;
705
+ }
706
+ const recordByteSize = Math.max(1, Math.ceil(totalBits / 8));
707
+ this._recordByteSize = recordByteSize;
708
+ this._indexBuffer = Buffer.alloc(numRows * recordByteSize);
709
+ const progressInterval = Math.max(1, Math.floor(numRows / 100));
710
+ for (let row = 0, recordBase = 0; row < numRows; row++, recordBase += recordByteSize) {
711
+ const values = data[row];
712
+ for (let column = 0; column < numColumns; column++) {
713
+ const value = values?.[column];
714
+ if (value === null || value === void 0) {
715
+ continue;
666
716
  }
667
- const paddingWidth = (8 - bits.length % 8) % 8;
668
- const paddedBits = bits.padStart(bits.length + paddingWidth, "0");
669
- const bytes = paddedBits.match(/.{1,8}/g)?.map((byte) => parseInt(byte, 2));
670
- bytes?.reverse();
671
- assert(bytes, "Byte conversion of bit indices failed.");
672
- return Buffer.from(Uint8Array.from(bytes));
673
- })
674
- );
675
- this._recordByteSize = this._indexTable.length > 0 ? this._indexBuffer.length / this._indexTable.length : 1;
717
+ const index = this._symbolIndexByValue[column].get(value);
718
+ if (index === void 0) {
719
+ throw new QvdValidationError("A value is missing from the symbol table", {
720
+ field: columns[column],
721
+ row,
722
+ file: this._path,
723
+ stage: "buildIndexTable"
724
+ });
725
+ }
726
+ writeBitField(this._indexBuffer, recordBase, layout[column].geometry, index + layout[column].nullShift);
727
+ }
728
+ if ((row + 1) % progressInterval === 0 || row + 1 === numRows) {
729
+ this._emitProgress("index-table", row + 1, numRows);
730
+ }
731
+ }
732
+ this._symbolIndexByValue = null;
676
733
  }
677
734
  /**
678
735
  * Converts a raw value/literal to a QVD symbol.
@@ -697,16 +754,6 @@ var init_QvdFileWriter = __esm({
697
754
  return QvdSymbol.fromStringValue(raw);
698
755
  }
699
756
  }
700
- /**
701
- * Converts an integer to a list of bits.
702
- *
703
- * @param {number} value The integer value to convert.
704
- * @param {number} width The width of the bit list.
705
- * @return {Array<number>} The list of bits.
706
- */
707
- static _convertInt32ToBits(value, width) {
708
- return value.toString(2).split("").map((bit) => parseInt(bit)).reverse().concat(new Array(width).fill(0)).slice(0, width).reverse();
709
- }
710
757
  /**
711
758
  * Persists the data frame to a QVD file.
712
759
  */
@@ -719,18 +766,6 @@ var init_QvdFileWriter = __esm({
719
766
  };
720
767
  }
721
768
  });
722
-
723
- // src/util/bitUtils.js
724
- function convertBitsToInt32(bits) {
725
- if (bits.length === 0) {
726
- return 0;
727
- }
728
- return bits.reduce((value, bit, index) => value += bit * Math.pow(2, index), 0);
729
- }
730
- var init_bitUtils = __esm({
731
- "src/util/bitUtils.js"() {
732
- }
733
- });
734
769
  function getHeapLimit() {
735
770
  return v8.getHeapStatistics().heap_size_limit;
736
771
  }
@@ -740,7 +775,7 @@ function heapLimitIsMeaningful() {
740
775
  function getMemoryBudget() {
741
776
  const candidates = [];
742
777
  if (heapLimitIsMeaningful()) {
743
- candidates.push({ source: "V8 heap limit", bytes: getHeapLimit() });
778
+ candidates.push({ source: "V8 heap limit", bytes: usableOldSpaceLimit() });
744
779
  }
745
780
  const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
746
781
  if (constrained > 0 && constrained < os.totalmem()) {
@@ -756,19 +791,56 @@ function getMemoryBudget() {
756
791
  const binding = candidates.reduce((lowest, candidate) => candidate.bytes < lowest.bytes ? candidate : lowest);
757
792
  return { bytes: binding.bytes, limitedBy: binding.source, candidates, observed };
758
793
  }
759
- function estimateMemoryUsage(symbolTableSize, maxRows, totalRows) {
794
+ function usableOldSpaceLimit() {
795
+ const usable = getHeapLimit() - HEAP_LIMIT_OVERSTATEMENT_BYTES;
796
+ return usable > MINIMUM_BUDGET_BYTES ? usable : MINIMUM_BUDGET_BYTES;
797
+ }
798
+ function estimateExternalMemory(rows, columnCount) {
799
+ if (!columnCount || columnCount <= 0 || !rows || rows <= 0) {
800
+ return 0;
801
+ }
802
+ return rows * columnCount * Int32Array.BYTES_PER_ELEMENT;
803
+ }
804
+ function estimateRowMemory(rows, columnCount) {
805
+ if (!columnCount || columnCount <= 0) {
806
+ return 0;
807
+ }
808
+ return BASE_BYTES + rows * (ROW_BASE_BYTES + PER_CELL_BYTES * columnCount);
809
+ }
810
+ function estimateMemoryUsage(symbolTableSize, maxRows, totalRows, columnCount = 0, materialisesRows = true) {
760
811
  const FULL_PARSE_OVERHEAD = 6;
761
812
  const MINIMAL_OVERHEAD = 0.01;
813
+ const rowsToLoad = maxRows === null || maxRows >= totalRows ? totalRows : maxRows;
814
+ const rowMemory = materialisesRows ? estimateRowMemory(rowsToLoad, columnCount) : BASE_BYTES;
762
815
  if (maxRows === null || maxRows >= totalRows) {
763
- return symbolTableSize * FULL_PARSE_OVERHEAD;
816
+ return symbolTableSize * FULL_PARSE_OVERHEAD + rowMemory;
764
817
  }
765
818
  const rowPercentage = maxRows / totalRows;
766
819
  const symbolPercentage = Math.sqrt(rowPercentage);
767
820
  const keptSymbolsMemory = symbolTableSize * symbolPercentage * FULL_PARSE_OVERHEAD;
768
821
  const skippedSymbolsMemory = symbolTableSize * (1 - symbolPercentage) * MINIMAL_OVERHEAD;
769
- return keptSymbolsMemory + skippedSymbolsMemory;
822
+ return keptSymbolsMemory + skippedSymbolsMemory + rowMemory;
770
823
  }
771
- function validateMemoryAvailability(symbolTableSize, maxRows, totalRows, filePath, safetyFactor = 0.3) {
824
+ function recommendedRowsFor(budget, symbolTableSize, totalRows, columnCount, materialisesRows = true) {
825
+ if (estimateMemoryUsage(symbolTableSize, totalRows, totalRows, columnCount, materialisesRows) <= budget) {
826
+ return totalRows;
827
+ }
828
+ if (estimateMemoryUsage(symbolTableSize, 0, totalRows, columnCount, materialisesRows) > budget) {
829
+ return 0;
830
+ }
831
+ let low = 0;
832
+ let high = totalRows;
833
+ while (high - low > 1) {
834
+ const mid = Math.floor((low + high) / 2);
835
+ if (estimateMemoryUsage(symbolTableSize, mid, totalRows, columnCount, materialisesRows) <= budget) {
836
+ low = mid;
837
+ } else {
838
+ high = mid;
839
+ }
840
+ }
841
+ return low;
842
+ }
843
+ function validateMemoryAvailability(symbolTableSize, maxRows, totalRows, filePath, safetyFactor = 0.8, columnCount = 0, materialisesRows = true) {
772
844
  if (typeof safetyFactor !== "number" || safetyFactor < 0 || safetyFactor > 1) {
773
845
  throw new QvdValidationError("safetyFactor must be a number between 0.0 and 1.0", { safetyFactor });
774
846
  }
@@ -776,25 +848,57 @@ function validateMemoryAvailability(symbolTableSize, maxRows, totalRows, filePat
776
848
  return;
777
849
  }
778
850
  const budget = getMemoryBudget();
851
+ const rowsToLoad = maxRows === null || maxRows >= totalRows ? totalRows : maxRows;
852
+ const heapMemory = estimateMemoryUsage(symbolTableSize, maxRows, totalRows, columnCount, materialisesRows);
853
+ const externalMemory = estimateExternalMemory(rowsToLoad, columnCount);
854
+ const bounded = budget.candidates.map((candidate) => {
855
+ const heapOnly = candidate.source === "V8 heap limit";
856
+ return {
857
+ ...candidate,
858
+ needs: heapOnly ? heapMemory : heapMemory + externalMemory,
859
+ allowed: candidate.bytes * safetyFactor,
860
+ bounds: heapOnly ? "the V8 heap" : "the whole process"
861
+ };
862
+ });
863
+ const exceeded = bounded.filter((candidate) => candidate.needs > candidate.allowed);
864
+ const binding = exceeded.reduce(
865
+ (worst, candidate) => candidate.needs / candidate.allowed > worst.needs / worst.allowed ? candidate : worst,
866
+ exceeded[0]
867
+ );
779
868
  const heapLimit = getHeapLimit();
780
- const availableMemory = budget.bytes;
781
- const estimatedMemory = estimateMemoryUsage(symbolTableSize, maxRows, totalRows);
782
- const maxAllowedMemory = budget.bytes * safetyFactor;
783
- if (estimatedMemory > maxAllowedMemory) {
784
- const safeSymbolPercentage = maxAllowedMemory / (symbolTableSize * 6);
785
- const safeRowPercentage = Math.pow(safeSymbolPercentage, 2);
786
- const recommendedMaxRows = Math.max(1, Math.floor(totalRows * safeRowPercentage));
869
+ const availableMemory = binding ? binding.bytes : budget.bytes;
870
+ const estimatedMemory = binding ? binding.needs : heapMemory;
871
+ const maxAllowedMemory = binding ? binding.allowed : budget.bytes * safetyFactor;
872
+ if (binding) {
873
+ const recommendedMaxRows = recommendedRowsFor(
874
+ maxAllowedMemory,
875
+ symbolTableSize,
876
+ totalRows,
877
+ columnCount,
878
+ materialisesRows
879
+ );
787
880
  const sizeMB = Math.round(symbolTableSize / 1024 / 1024);
788
881
  const estimatedMB = Math.round(estimatedMemory / 1024 / 1024);
789
882
  const availableMB = Math.round(maxAllowedMemory / 1024 / 1024);
790
- const heapLimitMB = Math.round(heapLimit / 1024 / 1024);
883
+ const heapLimitMB = Math.round(usableOldSpaceLimit() / 1024 / 1024);
884
+ const reportedHeapLimitMB = Math.round(heapLimit / 1024 / 1024);
791
885
  const availableRamMB = Math.round(availableMemory / 1024 / 1024);
792
- const limitingFactor = budget.limitedBy;
886
+ const limitingFactor = binding.source;
887
+ const limitingScope = binding.bounds;
793
888
  const budgetBreakdown = budget.candidates.map((candidate) => `${candidate.source} ${Math.round(candidate.bytes / 1024 / 1024)}MB`).join(", ");
794
889
  const observedBreakdown = budget.observed.map((entry) => `${entry.source} ${Math.round(entry.bytes / 1024 / 1024)}MB`).join(", ");
795
- const advice = limitingFactor === "container memory limit" ? `The binding limit is the container's, so raising --max-old-space-size would let V8 grow past it and be killed by the OOM killer instead. Set it below the container limit, raise the limit, or load fewer rows with maxRows (recommended: ${recommendedMaxRows.toLocaleString()} rows or less).` : `Try loading fewer rows using the maxRows parameter (recommended: ${recommendedMaxRows.toLocaleString()} rows or less), or raise the heap with --max-old-space-size.`;
890
+ const nothingFits = recommendedMaxRows === 0;
891
+ const containerBound = binding.source === "container memory limit";
892
+ let advice;
893
+ if (nothingFits) {
894
+ advice = `No row count fits this budget - the symbol table alone exceeds it, so maxRows cannot help. ` + (containerBound ? `Raise the container's memory limit.` : `Raise the heap with --max-old-space-size, or raise memorySafetyFactor.`);
895
+ } else if (containerBound) {
896
+ advice = `The binding limit is the container's, so raising --max-old-space-size would let V8 grow past it and be killed by the OOM killer instead. Set it below the container limit, raise the limit, or load fewer rows with maxRows (recommended: ${recommendedMaxRows.toLocaleString()} rows or less).`;
897
+ } else {
898
+ advice = `Try loading fewer rows using the maxRows parameter (recommended: ${recommendedMaxRows.toLocaleString()} rows or less), or raise the heap with --max-old-space-size.`;
899
+ }
796
900
  throw new QvdValidationError(
797
- `Insufficient memory to load file safely. Symbol table: ${sizeMB}MB, Estimated memory needed: ${estimatedMB}MB, Available: ${availableMB}MB (limited by ${limitingFactor}; considered: ${budgetBreakdown}; observed but not used: ${observedBreakdown}). ` + advice,
901
+ `Insufficient memory to load file safely. Symbol table: ${sizeMB}MB, Estimated memory needed: ${estimatedMB}MB, Available: ${availableMB}MB (limited by ${limitingFactor}, which bounds ${limitingScope}; considered: ${budgetBreakdown}; observed but not used: ${observedBreakdown}). ` + advice,
798
902
  {
799
903
  file: filePath,
800
904
  symbolTableSize,
@@ -802,10 +906,13 @@ function validateMemoryAvailability(symbolTableSize, maxRows, totalRows, filePat
802
906
  estimatedMemoryMB: estimatedMB,
803
907
  availableMemoryMB: availableMB,
804
908
  heapLimitMB,
909
+ reportedHeapLimitMB,
805
910
  availableRamMB,
806
911
  limitingFactor,
912
+ limitingScope,
807
913
  memoryBudget: budget.candidates,
808
914
  memoryObserved: budget.observed,
915
+ columnCount,
809
916
  totalRows,
810
917
  maxRows,
811
918
  recommendedMaxRows
@@ -813,12 +920,11 @@ function validateMemoryAvailability(symbolTableSize, maxRows, totalRows, filePat
813
920
  );
814
921
  }
815
922
  }
816
- function warnLargeSymbolTable(symbolTableSize, maxRows, totalRows) {
817
- const heapLimit = getHeapLimit();
818
- const LARGE_SYMBOL_TABLE_WARNING = heapLimit * 0.125;
923
+ function warnLargeSymbolTable(symbolTableSize, maxRows, totalRows, columnCount = 0, materialisesRows = true) {
924
+ const LARGE_SYMBOL_TABLE_WARNING = usableOldSpaceLimit() * 0.125;
819
925
  if (symbolTableSize > LARGE_SYMBOL_TABLE_WARNING && (maxRows === null || maxRows >= totalRows)) {
820
926
  const sizeMB = Math.round(symbolTableSize / 1024 / 1024);
821
- const estimatedMemory = estimateMemoryUsage(symbolTableSize, maxRows, totalRows);
927
+ const estimatedMemory = estimateMemoryUsage(symbolTableSize, maxRows, totalRows, columnCount, materialisesRows);
822
928
  const estimatedMB = Math.round(estimatedMemory / 1024 / 1024);
823
929
  const warnMB = Math.round(LARGE_SYMBOL_TABLE_WARNING / 1024 / 1024);
824
930
  console.warn(
@@ -826,13 +932,37 @@ function warnLargeSymbolTable(symbolTableSize, maxRows, totalRows) {
826
932
  );
827
933
  }
828
934
  }
935
+ var HEAP_LIMIT_OVERSTATEMENT_BYTES, MINIMUM_BUDGET_BYTES, BASE_BYTES, ROW_BASE_BYTES, PER_CELL_BYTES;
829
936
  var init_memoryUtils = __esm({
830
937
  "src/util/memoryUtils.js"() {
831
938
  init_QvdErrors();
939
+ HEAP_LIMIT_OVERSTATEMENT_BYTES = 192 * 1024 * 1024;
940
+ MINIMUM_BUDGET_BYTES = 64 * 1024 * 1024;
941
+ BASE_BYTES = 16 * 1024 * 1024;
942
+ ROW_BASE_BYTES = 72;
943
+ PER_CELL_BYTES = 8;
832
944
  }
833
945
  });
834
946
 
835
947
  // src/util/validationUtils.js
948
+ function validateHeaderStructure(headerObj, filePath, stage) {
949
+ const tableHeader = headerObj?.["QvdTableHeader"];
950
+ if (tableHeader === null || typeof tableHeader !== "object" || Array.isArray(tableHeader)) {
951
+ throw new QvdCorruptedError("The XML header contains no usable QvdTableHeader element", {
952
+ rootElements: headerObj && typeof headerObj === "object" ? Object.keys(headerObj) : [],
953
+ file: filePath,
954
+ stage
955
+ });
956
+ }
957
+ const symbolTableLength = parseInt(tableHeader["Offset"], 10);
958
+ if (isNaN(symbolTableLength) || !Number.isSafeInteger(symbolTableLength) || symbolTableLength < 0) {
959
+ throw new QvdCorruptedError("Invalid symbol table offset", {
960
+ offset: tableHeader["Offset"],
961
+ file: filePath,
962
+ stage
963
+ });
964
+ }
965
+ }
836
966
  function validateSymbolTableSizeEarly(symbolTableLength, filePath) {
837
967
  const heapLimit = getHeapLimit();
838
968
  const MAX_SYMBOL_TABLE_SIZE = heapLimit * 0.125;
@@ -906,6 +1036,15 @@ function validateFieldMetadata(field, symbolBufferLength, filePath) {
906
1036
  });
907
1037
  }
908
1038
  }
1039
+ function validateRecordCount(totalRows, filePath, stage = "parseIndexTable") {
1040
+ if (isNaN(totalRows) || !Number.isSafeInteger(totalRows) || totalRows < 0) {
1041
+ throw new QvdCorruptedError("Invalid number of records", {
1042
+ totalRows,
1043
+ file: filePath,
1044
+ stage
1045
+ });
1046
+ }
1047
+ }
909
1048
  function validateIndexTableMetadata(recordSize, totalRows, indexTableLength, indexTableOffset, bufferLength, rowsToLoad, filePath, fileSize = null) {
910
1049
  if (isNaN(recordSize) || !Number.isSafeInteger(recordSize) || recordSize < 0) {
911
1050
  throw new QvdCorruptedError("Invalid record byte size", {
@@ -914,13 +1053,7 @@ function validateIndexTableMetadata(recordSize, totalRows, indexTableLength, ind
914
1053
  stage: "parseIndexTable"
915
1054
  });
916
1055
  }
917
- if (isNaN(totalRows) || !Number.isSafeInteger(totalRows) || totalRows < 0) {
918
- throw new QvdCorruptedError("Invalid number of records", {
919
- totalRows,
920
- file: filePath,
921
- stage: "parseIndexTable"
922
- });
923
- }
1056
+ validateRecordCount(totalRows, filePath);
924
1057
  if (recordSize === 0 && totalRows > 0) {
925
1058
  throw new QvdCorruptedError("Record byte size cannot be zero when records exist", {
926
1059
  recordSize,
@@ -1016,6 +1149,24 @@ function validateFieldBitMetadata(field, recordSize, filePath) {
1016
1149
  stage: "parseIndexTable"
1017
1150
  });
1018
1151
  }
1152
+ const bias = parseInt(field["Bias"], 10);
1153
+ if (isNaN(bias) || !Number.isSafeInteger(bias)) {
1154
+ throw new QvdCorruptedError("Invalid bias", {
1155
+ field: field["FieldName"],
1156
+ bias: field["Bias"],
1157
+ file: filePath,
1158
+ stage: "parseIndexTable"
1159
+ });
1160
+ }
1161
+ if (bitWidth > MAX_BIT_WIDTH) {
1162
+ throw new QvdCorruptedError("Bit width exceeds maximum", {
1163
+ field: field["FieldName"],
1164
+ bitWidth,
1165
+ maxBitWidth: MAX_BIT_WIDTH,
1166
+ file: filePath,
1167
+ stage: "parseIndexTable"
1168
+ });
1169
+ }
1019
1170
  const recordSizeInBits = recordSize * 8;
1020
1171
  if (bitOffset + bitWidth > recordSizeInBits) {
1021
1172
  throw new QvdCorruptedError("Bit field extends beyond record size", {
@@ -1032,6 +1183,7 @@ var init_validationUtils = __esm({
1032
1183
  "src/util/validationUtils.js"() {
1033
1184
  init_QvdErrors();
1034
1185
  init_memoryUtils();
1186
+ init_bitUtils();
1035
1187
  }
1036
1188
  });
1037
1189
 
@@ -1291,6 +1443,273 @@ var init_symbolParser = __esm({
1291
1443
  }
1292
1444
  });
1293
1445
 
1446
+ // src/QvdColumnTable.js
1447
+ var QvdColumnTable_exports = {};
1448
+ __export(QvdColumnTable_exports, {
1449
+ QvdColumn: () => QvdColumn,
1450
+ QvdColumnTable: () => QvdColumnTable
1451
+ });
1452
+ var QvdColumn, QvdColumnTable;
1453
+ var init_QvdColumnTable = __esm({
1454
+ "src/QvdColumnTable.js"() {
1455
+ init_QvdErrors();
1456
+ QvdColumn = class {
1457
+ /**
1458
+ * @param {string} name The field name.
1459
+ * @param {Int32Array} codes One stored index per row, bias applied. Negative means NULL.
1460
+ * @param {Array<any>} symbols The field's distinct values, indexed by code.
1461
+ */
1462
+ constructor(name, codes, symbols) {
1463
+ this._name = name;
1464
+ this._codes = codes;
1465
+ this._symbols = symbols;
1466
+ Object.freeze(this);
1467
+ }
1468
+ /** @return {string} The field name. */
1469
+ get name() {
1470
+ return this._name;
1471
+ }
1472
+ /** @return {number} Rows in the column. */
1473
+ get length() {
1474
+ return this._codes.length;
1475
+ }
1476
+ /**
1477
+ * The stored index of each row. Negative means NULL.
1478
+ *
1479
+ * The table's own array, not a copy - it is the thing that makes this cheap, and copying it
1480
+ * per call would defeat the point. Treat it as read-only.
1481
+ *
1482
+ * @return {Int32Array} One code per row.
1483
+ */
1484
+ get codes() {
1485
+ return this._codes;
1486
+ }
1487
+ /**
1488
+ * The field's distinct values, indexed by the codes.
1489
+ *
1490
+ * One entry per distinct value, not per row: a few thousand entries for a column of millions.
1491
+ *
1492
+ * @return {ReadonlyArray<any>} The dictionary.
1493
+ */
1494
+ get symbols() {
1495
+ return this._symbols;
1496
+ }
1497
+ /**
1498
+ * The value of one row.
1499
+ *
1500
+ * @param {number} row The row index.
1501
+ * @return {any} The value, or null where the file stores NULL.
1502
+ * @throws {QvdValidationError} If the row is not an integer within the column.
1503
+ */
1504
+ at(row) {
1505
+ if (!Number.isInteger(row) || row < 0 || row >= this._codes.length) {
1506
+ throw new QvdValidationError("Row index out of bounds", {
1507
+ column: this._name,
1508
+ row,
1509
+ length: this._codes.length
1510
+ });
1511
+ }
1512
+ const code = this._codes[row];
1513
+ return code < 0 ? null : this._symbols[code];
1514
+ }
1515
+ /**
1516
+ * Iterates the column's values without materialising it.
1517
+ *
1518
+ * @return {Iterator<any>} An iterator over the values, NULLs included as null.
1519
+ */
1520
+ [Symbol.iterator]() {
1521
+ const codes = this._codes;
1522
+ const symbols = this._symbols;
1523
+ let row = 0;
1524
+ return {
1525
+ next() {
1526
+ if (row >= codes.length) {
1527
+ return { done: true, value: void 0 };
1528
+ }
1529
+ const code = codes[row++];
1530
+ return { done: false, value: code < 0 ? null : symbols[code] };
1531
+ }
1532
+ };
1533
+ }
1534
+ /**
1535
+ * The column as a plain array of values, one per row.
1536
+ *
1537
+ * Lossless, and cell-for-cell what `QvdDataFrame.data[row][column]` would hold. The caller
1538
+ * owns the result; the table keeps no reference to it, so two calls return two arrays.
1539
+ *
1540
+ * @return {Array<any>} One value per row.
1541
+ */
1542
+ toArray() {
1543
+ const out = new Array(this._codes.length);
1544
+ for (let row = 0; row < this._codes.length; row++) {
1545
+ const code = this._codes[row];
1546
+ out[row] = code < 0 ? null : this._symbols[code];
1547
+ }
1548
+ return out;
1549
+ }
1550
+ /**
1551
+ * The dictionary as numbers, for scanning without materialising the column.
1552
+ *
1553
+ * One entry per *distinct* value, not per row - 17 KB for a column of 1.7 million rows with
1554
+ * 2,188 symbols - so this is the cheap conversion, where `toFloat64Array()` is the expensive
1555
+ * one. Non-numeric symbols become NaN, which is safe here in a way it is not per row: the
1556
+ * codes still distinguish NULL, and a caller that wants the blank back still has `symbols`.
1557
+ *
1558
+ * Scanning `codes` against this is the fastest way to read a column, because both sides are
1559
+ * contiguous typed arrays and the dictionary fits in cache:
1560
+ *
1561
+ * ```js
1562
+ * const codes = column.codes;
1563
+ * const values = column.numericSymbols();
1564
+ * let total = 0;
1565
+ * for (let row = 0; row < codes.length; row++) {
1566
+ * const code = codes[row];
1567
+ * if (code >= 0) {
1568
+ * const value = values[code];
1569
+ * if (!Number.isNaN(value)) total += value;
1570
+ * }
1571
+ * }
1572
+ * ```
1573
+ *
1574
+ * @return {Float64Array} One number per distinct symbol, NaN where the symbol is not a number.
1575
+ */
1576
+ numericSymbols() {
1577
+ const out = new Float64Array(this._symbols.length);
1578
+ for (let index = 0; index < this._symbols.length; index++) {
1579
+ const value = this._symbols[index];
1580
+ out[index] = typeof value === "number" ? value : NaN;
1581
+ }
1582
+ return out;
1583
+ }
1584
+ /**
1585
+ * The column as a `Float64Array`.
1586
+ *
1587
+ * Named for what it costs rather than offered as *the* representation, because it is lossy
1588
+ * and on real data it is lossy often: it cannot distinguish a blank from a number, and the
1589
+ * bundled taxi fixture has a column that is 43% blank. It therefore refuses by default
1590
+ * rather than quietly writing NaN over two fifths of a column.
1591
+ *
1592
+ * @param {Object} [options] Conversion options.
1593
+ * @param {'throw'|'nan'} [options.onNonNumeric='throw'] What to do with a value that is not a
1594
+ * number - including NULL. `'throw'` refuses and names the offending row; `'nan'` writes
1595
+ * NaN, which is the right choice only when the caller knows the column is numeric.
1596
+ * @return {Float64Array} One number per row.
1597
+ * @throws {QvdValidationError} If a value is not a number and `onNonNumeric` is `'throw'`.
1598
+ */
1599
+ toFloat64Array(options = {}) {
1600
+ const { onNonNumeric = "throw" } = options;
1601
+ if (onNonNumeric !== "throw" && onNonNumeric !== "nan") {
1602
+ throw new QvdValidationError('onNonNumeric must be "throw" or "nan"', {
1603
+ column: this._name,
1604
+ provided: onNonNumeric
1605
+ });
1606
+ }
1607
+ const out = new Float64Array(this._codes.length);
1608
+ for (let row = 0; row < this._codes.length; row++) {
1609
+ const code = this._codes[row];
1610
+ const value = code < 0 ? null : this._symbols[code];
1611
+ if (typeof value === "number") {
1612
+ out[row] = value;
1613
+ continue;
1614
+ }
1615
+ if (onNonNumeric === "throw") {
1616
+ throw new QvdValidationError("Column holds a value that is not a number", {
1617
+ column: this._name,
1618
+ row,
1619
+ value,
1620
+ type: value === null ? "null" : typeof value,
1621
+ hint: 'Pass {onNonNumeric: "nan"} to write NaN instead, or use toArray() to keep the value.'
1622
+ });
1623
+ }
1624
+ out[row] = NaN;
1625
+ }
1626
+ return out;
1627
+ }
1628
+ };
1629
+ QvdColumnTable = class {
1630
+ /**
1631
+ * @param {Object} decoded What the reader decoded.
1632
+ * @param {Array<string>} decoded.columns Field names, in file order.
1633
+ * @param {Array<Int32Array>} decoded.codesByField One code array per field.
1634
+ * @param {Array<Array<any>>} decoded.symbolsByField One dictionary per field.
1635
+ * @param {number} decoded.rowCount Rows decoded.
1636
+ * @param {any} decoded.metadata The raw QvdTableHeader.
1637
+ * @param {any} decoded.loadStats Statistics about the read.
1638
+ */
1639
+ constructor({ columns, codesByField, symbolsByField, rowCount, metadata, loadStats }) {
1640
+ this._columns = columns;
1641
+ this._codesByField = codesByField;
1642
+ this._symbolsByField = symbolsByField;
1643
+ this._rowCount = rowCount;
1644
+ this._metadata = metadata;
1645
+ this._loadStats = loadStats;
1646
+ }
1647
+ /**
1648
+ * Reads a QVD file as columns.
1649
+ *
1650
+ * @param {string} path The path to the QVD file.
1651
+ * @param {Object} [options] Loading options, with the same meanings they have on `fromQvd`.
1652
+ * @param {number|null} [options.maxRows] Maximum rows to decode.
1653
+ * @param {string} [options.allowedDir] Directory the path must resolve inside.
1654
+ * @param {number} [options.memorySafetyFactor] Fraction of the memory budget a load may use.
1655
+ * @param {number} [options.symbolFilteringThreshold] Symbol table size above which a limited
1656
+ * read switches to two-pass filtering.
1657
+ * @return {Promise<QvdColumnTable>} The file, as columns.
1658
+ */
1659
+ static async fromQvd(path3, options = {}) {
1660
+ const { QvdFileReader: QvdFileReader2 } = await Promise.resolve().then(() => (init_QvdFileReader(), QvdFileReader_exports));
1661
+ const reader = new QvdFileReader2(path3, {
1662
+ allowedDir: options.allowedDir,
1663
+ memorySafetyFactor: options.memorySafetyFactor,
1664
+ symbolFilteringThreshold: options.symbolFilteringThreshold,
1665
+ // This read builds no rows, so the memory guard must not charge it for them. A columnar
1666
+ // read of the 38MB taxi fixture completes in a 15MB heap; charged the row cost it was
1667
+ // refused below a 2GB one.
1668
+ materialisesRows: false
1669
+ });
1670
+ return await reader.loadColumnar(options.maxRows !== void 0 ? options.maxRows : null);
1671
+ }
1672
+ /** @return {Array<string>} Field names, in file order. */
1673
+ get columns() {
1674
+ return this._columns;
1675
+ }
1676
+ /** @return {number} Rows decoded. */
1677
+ get rowCount() {
1678
+ return this._rowCount;
1679
+ }
1680
+ /** @return {Array<number>} `[rows, columns]`, as on a data frame. */
1681
+ get shape() {
1682
+ return [this._rowCount, this._columns.length];
1683
+ }
1684
+ /** @return {any} The raw `QvdTableHeader`. */
1685
+ get metadata() {
1686
+ return this._metadata;
1687
+ }
1688
+ /** @return {any} Statistics about the read. */
1689
+ get loadStats() {
1690
+ return this._loadStats;
1691
+ }
1692
+ /**
1693
+ * One column.
1694
+ *
1695
+ * @param {string} name The field name.
1696
+ * @return {QvdColumn} The column.
1697
+ * @throws {QvdValidationError} If the field is not in this file.
1698
+ */
1699
+ column(name) {
1700
+ const index = this._columns.indexOf(name);
1701
+ if (index === -1) {
1702
+ throw new QvdValidationError(`Column '${name}' does not exist`, {
1703
+ column: name,
1704
+ availableColumns: this._columns
1705
+ });
1706
+ }
1707
+ return new QvdColumn(name, this._codesByField[index], this._symbolsByField[index]);
1708
+ }
1709
+ };
1710
+ }
1711
+ });
1712
+
1294
1713
  // src/QvdFileReader.js
1295
1714
  var QvdFileReader_exports = {};
1296
1715
  __export(QvdFileReader_exports, {
@@ -1325,13 +1744,22 @@ var init_QvdFileReader = __esm({
1325
1744
  * check entirely**, which is the escape hatch for runtimes whose limits cannot be measured -
1326
1745
  * Bun reports its current heap as its heap limit - and for callers who would rather manage
1327
1746
  * memory themselves than trust the estimate.
1747
+ * @param {boolean} [options.materialisesRows=true] Whether this read will build row arrays.
1748
+ * False for a columnar read, whose memory is TypedArray backing stores outside the V8 heap
1749
+ * and which must not be charged the row cost.
1328
1750
  * @param {number} [options.symbolFilteringThreshold=52428800] Symbol table size, in bytes,
1329
1751
  * above which a lazy load switches to the two-pass filtering path. The default of 50MB is
1330
1752
  * the point where the extra analysis pass pays for itself; lower it to use filtering on
1331
1753
  * smaller files, raise it to keep the simpler single-pass read for longer.
1332
1754
  */
1333
1755
  constructor(filePath, options = {}) {
1334
- const { allowedDir, memorySafetyFactor = 0.3, symbolFilteringThreshold = 50 * 1024 * 1024 } = options;
1756
+ const {
1757
+ allowedDir,
1758
+ memorySafetyFactor = 0.8,
1759
+ symbolFilteringThreshold = 50 * 1024 * 1024,
1760
+ materialisesRows = true
1761
+ } = options;
1762
+ this._materialisesRows = materialisesRows;
1335
1763
  this._path = validatePath(filePath, allowedDir);
1336
1764
  this._memorySafetyFactor = memorySafetyFactor;
1337
1765
  this._symbolFilteringThreshold = symbolFilteringThreshold;
@@ -1341,8 +1769,10 @@ var init_QvdFileReader = __esm({
1341
1769
  this._indexTableOffset = null;
1342
1770
  this._header = null;
1343
1771
  this._symbolTable = null;
1344
- this._indexTable = null;
1772
+ this._indexColumns = null;
1773
+ this._rowsDecoded = 0;
1345
1774
  this._fileSize = null;
1775
+ this._headerMatchesFile = false;
1346
1776
  }
1347
1777
  /**
1348
1778
  * Reads the binary data of the QVD file.
@@ -1369,14 +1799,13 @@ var init_QvdFileReader = __esm({
1369
1799
  * - Direct byte-range reading for remaining data is fastest
1370
1800
  *
1371
1801
  * @param {number|null} maxRows The maximum number of rows to load. If null, all data is loaded.
1802
+ * @param {boolean} [headerOnly=false] Stop once the XML header has been read, leaving the
1803
+ * symbol and index tables on disk. This is the metadata-only path: the header is a few
1804
+ * kilobytes whatever the file's size, so reading a schema costs the same for a 40MB file as
1805
+ * for a 40GB one.
1372
1806
  * @private
1373
1807
  */
1374
- async _readData(maxRows = null) {
1375
- if (maxRows === null) {
1376
- this._buffer = await fs.promises.readFile(this._path);
1377
- this._fileSize = this._buffer.length;
1378
- return;
1379
- }
1808
+ async _readData(maxRows = null, headerOnly = false) {
1380
1809
  const HEADER_DELIMITER = "\r\n\0";
1381
1810
  const CHUNK_SIZE = 64 * 1024;
1382
1811
  const stream = fs.createReadStream(this._path, {
@@ -1385,7 +1814,6 @@ var init_QvdFileReader = __esm({
1385
1814
  const headerChunks = [];
1386
1815
  let headerBytes = 0;
1387
1816
  let tail = Buffer.alloc(0);
1388
- let headerBuffer = Buffer.alloc(0);
1389
1817
  let headerDelimiterIndex = -1;
1390
1818
  try {
1391
1819
  for await (const chunk of stream) {
@@ -1429,7 +1857,7 @@ var init_QvdFileReader = __esm({
1429
1857
  }
1430
1858
  );
1431
1859
  }
1432
- headerBuffer = Buffer.concat(headerChunks);
1860
+ const headerBuffer = Buffer.concat(headerChunks);
1433
1861
  const headerEndIndex = headerDelimiterIndex + HEADER_DELIMITER.length;
1434
1862
  const headerXml = headerBuffer.subarray(0, headerEndIndex).toString();
1435
1863
  const headerObj = await xml2.parseStringPromise(headerXml, { explicitArray: false });
@@ -1439,11 +1867,45 @@ var init_QvdFileReader = __esm({
1439
1867
  stage: "readData"
1440
1868
  });
1441
1869
  }
1870
+ validateHeaderStructure(headerObj, this._path, "readData");
1442
1871
  const symbolTableOffset = headerEndIndex;
1443
1872
  const symbolTableLength = parseInt(headerObj["QvdTableHeader"]["Offset"], 10);
1444
1873
  const indexTableOffset = symbolTableOffset + symbolTableLength;
1445
1874
  const recordSize = parseInt(headerObj["QvdTableHeader"]["RecordByteSize"], 10);
1446
1875
  const totalRows = parseInt(headerObj["QvdTableHeader"]["NoOfRecords"], 10);
1876
+ if (headerOnly) {
1877
+ this._buffer = headerBuffer.subarray(0, headerEndIndex);
1878
+ return;
1879
+ }
1880
+ let headerFields = headerObj["QvdTableHeader"]?.["Fields"]?.["QvdFieldHeader"];
1881
+ if (headerFields && !Array.isArray(headerFields)) {
1882
+ headerFields = [headerFields];
1883
+ }
1884
+ const columnCount = Array.isArray(headerFields) ? headerFields.length : 0;
1885
+ const headerNumbersUsable = [symbolTableLength, recordSize, totalRows].every(
1886
+ (value) => Number.isSafeInteger(value) && value >= 0
1887
+ );
1888
+ if (headerNumbersUsable) {
1889
+ const { size: fileSize } = await fs.promises.stat(this._path);
1890
+ this._fileSize = fileSize;
1891
+ this._headerMatchesFile = headerEndIndex + symbolTableLength + totalRows * recordSize <= fileSize;
1892
+ }
1893
+ if (headerNumbersUsable && this._headerMatchesFile) {
1894
+ validateMemoryAvailability(
1895
+ symbolTableLength,
1896
+ maxRows,
1897
+ totalRows,
1898
+ this._path,
1899
+ this._memorySafetyFactor,
1900
+ columnCount,
1901
+ this._materialisesRows
1902
+ );
1903
+ }
1904
+ if (maxRows === null) {
1905
+ this._buffer = await fs.promises.readFile(this._path);
1906
+ this._fileSize = this._buffer.length;
1907
+ return;
1908
+ }
1447
1909
  const rowsToLoad = Math.min(maxRows, totalRows);
1448
1910
  validateSymbolTableSizeEarly(symbolTableLength, this._path);
1449
1911
  for (const [name, value] of [
@@ -1529,38 +1991,52 @@ var init_QvdFileReader = __esm({
1529
1991
  stage: "parseHeader"
1530
1992
  });
1531
1993
  }
1994
+ validateHeaderStructure(this._header, this._path, "parseHeader");
1995
+ const fields = this._header["QvdTableHeader"]?.["Fields"]?.["QvdFieldHeader"];
1996
+ const fieldList = fields === void 0 || fields === null ? [] : Array.isArray(fields) ? fields : [fields];
1997
+ if (fieldList.length === 0) {
1998
+ throw new QvdCorruptedError("The QVD file header declares no fields", {
1999
+ file: this._path,
2000
+ stage: "parseHeader"
2001
+ });
2002
+ }
2003
+ const malformedIndex = fieldList.findIndex(
2004
+ (field) => field === null || typeof field !== "object" || Array.isArray(field)
2005
+ );
2006
+ if (malformedIndex !== -1) {
2007
+ throw new QvdCorruptedError("The QVD file header declares a field with no properties", {
2008
+ fieldIndex: malformedIndex,
2009
+ fieldCount: fieldList.length,
2010
+ file: this._path,
2011
+ stage: "parseHeader"
2012
+ });
2013
+ }
1532
2014
  this._headerOffset = headerBeginIndex;
1533
2015
  this._symbolTableOffset = headerEndIndex;
1534
2016
  this._indexTableOffset = this._symbolTableOffset + parseInt(this._header["QvdTableHeader"]["Offset"], 10);
1535
2017
  }
1536
2018
  /**
1537
- * Estimates the memory usage for loading a QVD file with given parameters.
1538
- * Takes into account Phase 2.5 optimization which skips parsing unused symbols.
2019
+ * Establishes the geometry of the index table, and validates it.
1539
2020
  *
1540
- * @param {number} symbolTableSize Size of symbol table in bytes
1541
- * @param {number|null} maxRows Maximum number of rows to load (null = all rows)
1542
- * @param {number} totalRows Total number of rows in the file
1543
- * @returns {number} Estimated memory usage in bytes
1544
- * @private
1545
- */
1546
- _estimateMemoryUsage(symbolTableSize, maxRows, totalRows) {
1547
- return estimateMemoryUsage(symbolTableSize, maxRows, totalRows);
1548
- }
1549
- /**
1550
- * Analyzes the index table to determine which symbols are actually needed.
1551
- * This is used for two-pass symbol filtering optimization.
2021
+ * Both passes over the index table - the symbol-usage analysis and the decode itself - need
2022
+ * exactly this, and they used to derive it separately with two copies of the same bit
2023
+ * unpacking. The copies are the reason the bias comment in the analysis pass warns so loudly
2024
+ * about keeping the sign in step with the other one: the two could drift, and #113 is what
2025
+ * that looks like when they do. There is one copy now.
1552
2026
  *
1553
- * @param {number} maxRows The maximum number of rows to analyze.
1554
- * @returns {Promise<Map<string, Set<number>>>} Map of field names to Set of needed symbol indices.
2027
+ * @param {number|null} rowLimit Maximum rows of interest, or null for all of them.
2028
+ * @param {string} stage Stage name for any error raised here.
2029
+ * @return {{fields: Array<any>, recordSize: number, totalRows: number, rowsToLoad: number,
2030
+ * indexBuffer: Buffer}} The record geometry.
1555
2031
  * @private
1556
2032
  */
1557
- async _analyzeIndexTableSymbolUsage(maxRows) {
2033
+ _planIndexTable(rowLimit, stage) {
1558
2034
  if (!this._buffer || !this._header || !this._indexTableOffset) {
1559
2035
  throw new QvdCorruptedError(
1560
2036
  "The QVD file has not been loaded in the proper order or has not been loaded at all.",
1561
2037
  {
1562
2038
  file: this._path,
1563
- stage: "analyzeIndexTableSymbolUsage"
2039
+ stage
1564
2040
  }
1565
2041
  );
1566
2042
  }
@@ -1570,35 +2046,58 @@ var init_QvdFileReader = __esm({
1570
2046
  }
1571
2047
  const recordSize = parseInt(this._header["QvdTableHeader"]["RecordByteSize"], 10);
1572
2048
  const totalRows = parseInt(this._header["QvdTableHeader"]["NoOfRecords"], 10);
1573
- const rowsToAnalyze = Math.min(maxRows, totalRows);
2049
+ const rowsToLoad = rowLimit !== null ? Math.min(rowLimit, totalRows) : totalRows;
1574
2050
  const indexTableLength = parseInt(this._header["QvdTableHeader"]["Length"], 10);
2051
+ validateIndexTableMetadata(
2052
+ recordSize,
2053
+ totalRows,
2054
+ indexTableLength,
2055
+ this._indexTableOffset,
2056
+ this._buffer.length,
2057
+ rowsToLoad,
2058
+ this._path,
2059
+ this._fileSize
2060
+ );
1575
2061
  const indexBuffer = this._buffer.subarray(this._indexTableOffset, this._indexTableOffset + indexTableLength + 1);
2062
+ for (const field of fields) {
2063
+ validateFieldBitMetadata(field, recordSize, this._path);
2064
+ }
2065
+ assert2(
2066
+ rowsToLoad === 0 || recordSize === 0 || Math.floor(indexBuffer.length / recordSize) >= rowsToLoad,
2067
+ `The index table holds ${Math.floor(indexBuffer.length / (recordSize || 1))} whole records but ${rowsToLoad} were validated as present.`
2068
+ );
2069
+ return { fields, recordSize, totalRows, rowsToLoad, indexBuffer };
2070
+ }
2071
+ /**
2072
+ * Analyzes the index table to determine which symbols are actually needed.
2073
+ * This is used for two-pass symbol filtering optimization.
2074
+ *
2075
+ * @param {number} maxRows The maximum number of rows to analyze.
2076
+ * @return {Promise<Map<string, Set<number>>>} Map of field names to Set of needed symbol indices.
2077
+ * @private
2078
+ */
2079
+ async _analyzeIndexTableSymbolUsage(maxRows) {
2080
+ const { fields, recordSize, rowsToLoad, indexBuffer } = this._planIndexTable(maxRows, "analyzeIndexTableSymbolUsage");
1576
2081
  const symbolUsage = /* @__PURE__ */ new Map();
2082
+ const column = new Int32Array(rowsToLoad);
1577
2083
  fields.forEach((field) => {
1578
- symbolUsage.set(field["FieldName"], /* @__PURE__ */ new Set());
1579
- });
1580
- for (let pointer = 0, rowCount = 0; pointer < indexBuffer.length && rowCount < rowsToAnalyze; pointer += recordSize, rowCount++) {
1581
- const bytes = new Int32Array(indexBuffer.subarray(pointer, pointer + recordSize));
1582
- bytes.reverse();
1583
- const mask = bytes.reduce((bits, byte) => bits + ("00000000" + byte.toString(2)).slice(-8), "").split("").reverse().map((bit) => parseInt(bit));
1584
- fields.forEach((field) => {
1585
- const bitOffset = parseInt(field["BitOffset"], 10);
1586
- const bitWidth = parseInt(field["BitWidth"], 10);
1587
- const bias = parseInt(field["Bias"], 10);
1588
- let symbolIndex;
1589
- if (bitWidth === 0) {
1590
- symbolIndex = 0;
1591
- } else {
1592
- symbolIndex = this._convertBitsToInt32(mask.slice(bitOffset, bitOffset + bitWidth));
1593
- }
1594
- symbolIndex += bias;
1595
- if (symbolIndex < 0) {
1596
- return;
2084
+ const needed = /* @__PURE__ */ new Set();
2085
+ symbolUsage.set(field["FieldName"], needed);
2086
+ decodeIndexColumn(
2087
+ indexBuffer,
2088
+ recordSize,
2089
+ rowsToLoad,
2090
+ parseInt(field["BitOffset"], 10),
2091
+ parseInt(field["BitWidth"], 10),
2092
+ parseInt(field["Bias"], 10),
2093
+ column
2094
+ );
2095
+ for (let row = 0; row < rowsToLoad; row++) {
2096
+ if (column[row] >= 0) {
2097
+ needed.add(column[row]);
1597
2098
  }
1598
- const fieldName = field["FieldName"];
1599
- symbolUsage.get(fieldName)?.add(symbolIndex);
1600
- });
1601
- }
2099
+ }
2100
+ });
1602
2101
  return symbolUsage;
1603
2102
  }
1604
2103
  /**
@@ -1624,8 +2123,24 @@ var init_QvdFileReader = __esm({
1624
2123
  const symbolTableSize = symbolBuffer.length;
1625
2124
  const totalRows = parseInt(this._header["QvdTableHeader"]["NoOfRecords"], 10);
1626
2125
  validateSymbolTableSize(symbolTableSize, this._path, totalRows);
1627
- validateMemoryAvailability(symbolTableSize, maxRows, totalRows, this._path, this._memorySafetyFactor);
1628
- warnLargeSymbolTable(symbolTableSize, maxRows, totalRows);
2126
+ if (this._headerMatchesFile) {
2127
+ validateMemoryAvailability(
2128
+ symbolTableSize,
2129
+ maxRows,
2130
+ totalRows,
2131
+ this._path,
2132
+ this._memorySafetyFactor,
2133
+ Array.isArray(fields) ? fields.length : 1,
2134
+ this._materialisesRows
2135
+ );
2136
+ }
2137
+ warnLargeSymbolTable(
2138
+ symbolTableSize,
2139
+ maxRows,
2140
+ totalRows,
2141
+ Array.isArray(fields) ? fields.length : 1,
2142
+ this._materialisesRows
2143
+ );
1629
2144
  if (!Array.isArray(fields)) {
1630
2145
  fields = [fields];
1631
2146
  }
@@ -1659,93 +2174,85 @@ var init_QvdFileReader = __esm({
1659
2174
  return symbols;
1660
2175
  });
1661
2176
  }
1662
- /**
1663
- * Utility method to convert a bit array to an integer value.
1664
- *
1665
- * @param {Array<number>} bits The bit array
1666
- * @return {Number} The integer value
1667
- */
1668
- _convertBitsToInt32(bits) {
1669
- return convertBitsToInt32(bits);
1670
- }
1671
2177
  /**
1672
2178
  * Parses the bit stuffed index table of the QVD file. This method is part of the parsing process
1673
2179
  * and should not be called directly.
1674
2180
  *
2181
+ * One `Int32Array` per field, filled by `decodeIndexColumn`, replacing an array per row filled
2182
+ * a bit at a time. The old route, per row, built an `Int32Array` of the record's bytes,
2183
+ * concatenated a binary string of `recordSize * 8` characters, split it into a character
2184
+ * array, reversed that, and mapped it to one number per *bit*; then per cell it sliced the
2185
+ * result again and summed `bit * Math.pow(2, index)`. Several arrays the length of the record
2186
+ * in bits, built and discarded for every row.
2187
+ *
2188
+ * Column-major is what makes the decode tight: a field's bit offset, width and bias are the
2189
+ * same for every row, so they are hoisted out of the loop and the inner loop does arithmetic
2190
+ * into a typed array and nothing else. Rows are assembled later, once, in `load()`.
2191
+ *
1675
2192
  * @param {number|null} maxRows The maximum number of rows to parse. If null, all rows are parsed.
1676
2193
  */
1677
2194
  async _parseIndexTable(maxRows = null) {
1678
- if (!this._buffer || !this._header || !this._indexTableOffset) {
1679
- throw new QvdCorruptedError(
1680
- "The QVD file has not been loaded in the proper order or has not been loaded at all.",
1681
- {
1682
- file: this._path,
1683
- stage: "parseIndexTable"
1684
- }
1685
- );
1686
- }
1687
- let fields = this._header["QvdTableHeader"]["Fields"]["QvdFieldHeader"];
2195
+ const { fields, recordSize, rowsToLoad, indexBuffer } = this._planIndexTable(maxRows, "parseIndexTable");
2196
+ this._rowsDecoded = rowsToLoad;
2197
+ this._indexColumns = fields.map(
2198
+ (field) => decodeIndexColumn(
2199
+ indexBuffer,
2200
+ recordSize,
2201
+ rowsToLoad,
2202
+ parseInt(field["BitOffset"], 10),
2203
+ parseInt(field["BitWidth"], 10),
2204
+ parseInt(field["Bias"], 10),
2205
+ new Int32Array(rowsToLoad)
2206
+ )
2207
+ );
2208
+ }
2209
+ /**
2210
+ * Reads the file's schema and header metadata, without touching the symbol or index tables.
2211
+ *
2212
+ * Constant cost in the size of the file. `fromQvd(path, {maxRows: 0})` is not the same thing
2213
+ * and never was: the lazy path reads `headerEnd + symbolTableLength + rowsToLoad * recordSize`
2214
+ * bytes, so it still pulls the entire symbol table - 0.4MB on the taxi fixture, but hundreds
2215
+ * of megabytes on a high-cardinality file, and it has to be parsed as well as read.
2216
+ *
2217
+ * The memory check is deliberately not run for this. It sizes the rows a call will
2218
+ * materialise, and this materialises none; applying it would let a file too large to load
2219
+ * refuse to say what is in it.
2220
+ *
2221
+ * @return {Promise<import('./QvdDataFrame.js').QvdFileMetadata>} The file's schema and header.
2222
+ */
2223
+ async loadMetadata() {
2224
+ await this._readData(null, true);
2225
+ await this._parseHeader();
2226
+ assert2(this._header, "The QVD file header has not been parsed.");
2227
+ const header = this._header["QvdTableHeader"];
2228
+ let fields = header["Fields"]?.["QvdFieldHeader"] ?? [];
1688
2229
  if (!Array.isArray(fields)) {
1689
2230
  fields = [fields];
1690
2231
  }
1691
- const recordSize = parseInt(this._header["QvdTableHeader"]["RecordByteSize"], 10);
1692
- const totalRows = parseInt(this._header["QvdTableHeader"]["NoOfRecords"], 10);
1693
- const rowsToLoad = maxRows !== null ? Math.min(maxRows, totalRows) : totalRows;
1694
- const indexTableLength = parseInt(this._header["QvdTableHeader"]["Length"], 10);
1695
- validateIndexTableMetadata(
1696
- recordSize,
1697
- totalRows,
1698
- indexTableLength,
1699
- this._indexTableOffset,
1700
- this._buffer.length,
1701
- rowsToLoad,
1702
- this._path,
1703
- this._fileSize
1704
- );
1705
- const indexBuffer = this._buffer.subarray(this._indexTableOffset, this._indexTableOffset + indexTableLength + 1);
1706
- for (const field of fields) {
1707
- validateFieldBitMetadata(field, recordSize, this._path);
1708
- }
1709
- this._indexTable = [];
1710
- for (let pointer = 0, rowCount = 0; pointer < indexBuffer.length && rowCount < rowsToLoad; pointer += recordSize, rowCount++) {
1711
- if (pointer + recordSize > indexBuffer.length) {
1712
- throw new QvdCorruptedError("Buffer overflow reading index table record", {
1713
- pointer,
1714
- recordSize,
1715
- bufferSize: indexBuffer.length,
1716
- file: this._path,
1717
- stage: "parseIndexTable"
1718
- });
1719
- }
1720
- const bytes = new Int32Array(indexBuffer.subarray(pointer, pointer + recordSize));
1721
- bytes.reverse();
1722
- const mask = bytes.reduce((bits, byte) => bits + ("00000000" + byte.toString(2)).slice(-8), "").split("").reverse().map((bit) => parseInt(bit));
1723
- const symbolIndices = [];
1724
- fields.forEach((field) => {
1725
- const bitOffset = parseInt(field["BitOffset"], 10);
1726
- const bitWidth = parseInt(field["BitWidth"], 10);
1727
- const bias = parseInt(field["Bias"], 10);
1728
- let symbolIndex;
1729
- if (bitWidth === 0) {
1730
- symbolIndex = 0;
1731
- } else {
1732
- symbolIndex = this._convertBitsToInt32(mask.slice(bitOffset, bitOffset + bitWidth));
1733
- }
1734
- symbolIndex += bias;
1735
- symbolIndices.push(symbolIndex);
1736
- });
1737
- this._indexTable.push(symbolIndices);
1738
- }
1739
- if (this._indexTable.length !== rowsToLoad) {
1740
- throw new QvdCorruptedError("Index table contains fewer records than expected", {
1741
- expectedRows: rowsToLoad,
1742
- actualRows: this._indexTable.length,
1743
- totalRows,
1744
- recordSize,
2232
+ if (fields.length === 0) {
2233
+ throw new QvdCorruptedError("The QVD file header declares no fields", {
1745
2234
  file: this._path,
1746
- stage: "parseIndexTable"
2235
+ stage: "readMetadata"
1747
2236
  });
1748
2237
  }
2238
+ const columns = fields.map((field) => field["FieldName"]);
2239
+ const rowCount = parseInt(header["NoOfRecords"], 10);
2240
+ validateRecordCount(rowCount, this._path, "readMetadata");
2241
+ const shape = new QvdDataFrame([], columns, header, {
2242
+ symbolTableBytes: parseInt(header["Offset"], 10),
2243
+ totalRows: rowCount,
2244
+ rowsLoaded: 0,
2245
+ symbolFiltering: false,
2246
+ symbolsKept: null
2247
+ });
2248
+ return {
2249
+ columns,
2250
+ rowCount,
2251
+ columnCount: columns.length,
2252
+ fields: columns.map((name) => shape.getFieldMetadata(name)),
2253
+ fileMetadata: shape.fileMetadata,
2254
+ metadata: header
2255
+ };
1749
2256
  }
1750
2257
  /**
1751
2258
  * Loads the QVD file into memory and parses it.
@@ -1756,6 +2263,37 @@ var init_QvdFileReader = __esm({
1756
2263
  * @return {Promise<QvdDataFrame>} The loaded QVD file.
1757
2264
  */
1758
2265
  async load(maxRows = null) {
2266
+ const { columns, metadata, loadStats, resolvedByField } = await this._decode(maxRows);
2267
+ assert2(this._indexColumns, "The QVD file index table has not been parsed.");
2268
+ const indexColumns = this._indexColumns;
2269
+ const fieldCount = indexColumns.length;
2270
+ const data = new Array(this._rowsDecoded);
2271
+ for (let row = 0; row < this._rowsDecoded; row++) {
2272
+ const values = new Array(fieldCount);
2273
+ for (let field = 0; field < fieldCount; field++) {
2274
+ const symbolIndex = indexColumns[field][row];
2275
+ values[field] = symbolIndex < 0 ? null : resolvedByField[field][symbolIndex];
2276
+ }
2277
+ data[row] = values;
2278
+ }
2279
+ loadStats.rowsLoaded = data.length;
2280
+ return new QvdDataFrame(data, columns, metadata, loadStats);
2281
+ }
2282
+ /**
2283
+ * Reads and decodes the file, stopping short of building rows.
2284
+ *
2285
+ * Everything `load()` and `loadColumnar()` have in common, which is everything except the
2286
+ * shape of the answer. Two read paths for one binary format is the drift risk #113 is the
2287
+ * standing example of - a stored index resolved one way here and another way there returns
2288
+ * plausible wrong values and throws nothing - so there is one path, and the two entry points
2289
+ * differ only in what they do with what it returns.
2290
+ *
2291
+ * @param {number|null} maxRows Maximum rows to decode, or null for all of them.
2292
+ * @return {Promise<{columns: Array<string>, metadata: any, loadStats: any,
2293
+ * resolvedByField: Array<Array<any>>}>} The decoded file.
2294
+ * @private
2295
+ */
2296
+ async _decode(maxRows = null) {
1759
2297
  if (maxRows !== null && (typeof maxRows !== "number" || !Number.isInteger(maxRows) || maxRows < 0)) {
1760
2298
  throw new QvdValidationError("maxRows must be a non-negative integer, or null to load all rows", {
1761
2299
  provided: maxRows,
@@ -1776,46 +2314,57 @@ var init_QvdFileReader = __esm({
1776
2314
  }
1777
2315
  await this._parseSymbolTable(symbolsToKeep, maxRows);
1778
2316
  await this._parseIndexTable(maxRows);
1779
- assert(this._header, "The QVD file header has not been parsed.");
1780
- assert(this._symbolTable, "The QVD file symbol table has not been parsed.");
1781
- assert(this._indexTable, "The QVD file index table has not been parsed.");
1782
- const getRow = (index) => {
1783
- if (!this._indexTable || index >= this._indexTable.length) {
1784
- throw new QvdValidationError("Row index out of bounds", {
1785
- index,
1786
- max: this._indexTable ? this._indexTable.length - 1 : -1,
1787
- file: this._path
1788
- });
2317
+ assert2(this._header, "The QVD file header has not been parsed.");
2318
+ assert2(this._symbolTable, "The QVD file symbol table has not been parsed.");
2319
+ assert2(this._indexColumns, "The QVD file index table has not been parsed.");
2320
+ const resolvedByField = this._symbolTable.map((symbols) => {
2321
+ const resolved = new Array(symbols.length);
2322
+ for (let index = 0; index < symbols.length; index++) {
2323
+ const value = symbols[index]?.toPrimaryValue();
2324
+ resolved[index] = typeof value === "string" && value.trim() !== "" && !isNaN(Number(value)) ? Number(value) : value;
1789
2325
  }
1790
- return this._indexTable?.[index].map((symbolIndex, fieldIndex) => {
1791
- if (symbolIndex < 0) {
1792
- return null;
1793
- }
1794
- const symbol = this._symbolTable?.[fieldIndex]?.[symbolIndex];
1795
- const value = symbol?.toPrimaryValue();
1796
- if (typeof value === "string") {
1797
- if (value.trim() !== "" && !isNaN(Number(value))) {
1798
- return Number(value);
1799
- }
1800
- }
1801
- return value;
1802
- });
1803
- };
2326
+ return resolved;
2327
+ });
1804
2328
  let fields = this._header["QvdTableHeader"]["Fields"]["QvdFieldHeader"];
1805
2329
  if (!Array.isArray(fields)) {
1806
2330
  fields = [fields];
1807
2331
  }
1808
2332
  const columns = fields.map((field) => field["FieldName"]);
1809
- const data = this._indexTable.map((_, index) => getRow(index));
1810
2333
  const metadata = this._header["QvdTableHeader"];
1811
2334
  const loadStats = {
1812
2335
  symbolTableBytes: parseInt(this._header["QvdTableHeader"]["Offset"], 10),
1813
2336
  totalRows: parseInt(this._header["QvdTableHeader"]["NoOfRecords"], 10),
1814
- rowsLoaded: data.length,
2337
+ rowsLoaded: this._rowsDecoded,
1815
2338
  symbolFiltering: symbolsToKeep !== null,
1816
2339
  symbolsKept
1817
2340
  };
1818
- return new QvdDataFrame(data, columns, metadata, loadStats);
2341
+ return { columns, metadata, loadStats, resolvedByField };
2342
+ }
2343
+ /**
2344
+ * Reads the file as columns, without ever materialising rows.
2345
+ *
2346
+ * Shares every step with `load()` up to the point where rows would be built - see `_decode`.
2347
+ * What it keeps instead is what the decoder already produced: one `Int32Array` of stored
2348
+ * indices per field, and one resolved value per distinct symbol. On the 1.7M x 20 taxi
2349
+ * fixture that is 38.6 MiB against the 352.8 MiB `data` retains, because a column costs four
2350
+ * bytes per row rather than a boxed value per cell, and the symbols are a few thousand
2351
+ * entries shared across every row that uses them.
2352
+ *
2353
+ * @param {number|null} maxRows The maximum number of rows to decode.
2354
+ * @return {Promise<import('./QvdColumnTable.js').QvdColumnTable>} The decoded columns.
2355
+ */
2356
+ async loadColumnar(maxRows = null) {
2357
+ const { columns, metadata, loadStats, resolvedByField } = await this._decode(maxRows);
2358
+ const { QvdColumnTable: QvdColumnTable2 } = await Promise.resolve().then(() => (init_QvdColumnTable(), QvdColumnTable_exports));
2359
+ assert2(this._indexColumns, "The QVD file index table has not been parsed.");
2360
+ return new QvdColumnTable2({
2361
+ columns,
2362
+ codesByField: this._indexColumns,
2363
+ symbolsByField: resolvedByField,
2364
+ rowCount: this._rowsDecoded,
2365
+ metadata,
2366
+ loadStats
2367
+ });
1819
2368
  }
1820
2369
  };
1821
2370
  }
@@ -2255,10 +2804,11 @@ var init_QvdDataFrame = __esm({
2255
2804
  * outside it is rejected. Defaults to the current working directory. To permit an entire
2256
2805
  * volume, pass its root explicitly ('/' on POSIX, 'C:\\' on Windows); a null or empty value falls
2257
2806
  * back to the working directory rather than removing the restriction.
2258
- * @param {number} [options.memorySafetyFactor=0.3] Fraction (0.0-1.0) of the memory budget a load
2259
- * may use. The budget is the smallest of the V8 heap limit, any container memory limit, and the
2260
- * memory the OS reports as available. Default is 0.3; raise it when running with a larger heap via
2261
- * --max-old-space-size. **Zero disables the memory check entirely.**
2807
+ * @param {number} [options.memorySafetyFactor=0.8] Fraction (0.0-1.0) of the memory budget a load
2808
+ * may use. The budget is the smaller of the V8 heap limit and any container memory limit. Default
2809
+ * is 0.8; the estimate it scales accounts for the rows and columns being materialised, so this is
2810
+ * headroom for garbage collection rather than compensation for an inaccurate figure.
2811
+ * **Zero disables the memory check entirely.**
2262
2812
  * @param {number} [options.symbolFilteringThreshold=52428800] Symbol table size, in bytes, above which
2263
2813
  * a lazy load switches to the two-pass filtering path. Defaults to 50MB.
2264
2814
  * @throws {QvdValidationError} If options.maxRows is neither null/undefined nor a non-negative integer.
@@ -2273,6 +2823,34 @@ var init_QvdDataFrame = __esm({
2273
2823
  };
2274
2824
  return await new QvdFileReader2(path3, readerOptions).load(options.maxRows !== void 0 ? options.maxRows : null);
2275
2825
  }
2826
+ /**
2827
+ * Reads a QVD file's schema and header metadata, without reading its data.
2828
+ *
2829
+ * Costs the same whatever the file's size, because it stops at the XML header - a few
2830
+ * kilobytes - and never touches the symbol or index tables.
2831
+ *
2832
+ * This is what `{maxRows: 0}` looks like but is not. That still reads and parses the whole
2833
+ * symbol table, which is 0.4MB on a 38MB taxi fixture but hundreds of megabytes on a
2834
+ * high-cardinality file. Use this when you want to know what is in a file rather than to
2835
+ * read any of it.
2836
+ *
2837
+ * No data frame comes back, deliberately: one with `data: []` would be indistinguishable
2838
+ * from an empty file at the call site.
2839
+ *
2840
+ * ```js
2841
+ * const {columns, rowCount, fields} = await QvdDataFrame.readMetadata('sales.qvd');
2842
+ * ```
2843
+ *
2844
+ * @param {string} path The path to the QVD file.
2845
+ * @param {Object} [options] Optional reading options.
2846
+ * @param {string} [options.allowedDir] Optional allowed directory path, applied exactly as it
2847
+ * is for `fromQvd`.
2848
+ * @return {Promise<QvdFileMetadata>} The file's schema and header metadata.
2849
+ */
2850
+ static async readMetadata(path3, options = {}) {
2851
+ const { QvdFileReader: QvdFileReader2 } = await Promise.resolve().then(() => (init_QvdFileReader(), QvdFileReader_exports));
2852
+ return await new QvdFileReader2(path3, { allowedDir: options.allowedDir }).loadMetadata();
2853
+ }
2276
2854
  /**
2277
2855
  * Constructs a data frame from a dictionary.
2278
2856
  *
@@ -2299,10 +2877,11 @@ var init_QvdDataFrame = __esm({
2299
2877
  // src/index.js
2300
2878
  init_QvdSymbol();
2301
2879
  init_QvdDataFrame();
2880
+ init_QvdColumnTable();
2302
2881
  init_QvdFileReader();
2303
2882
  init_QvdFileWriter();
2304
2883
  init_QvdErrors();
2305
2884
 
2306
- export { QvdCorruptedError, QvdDataFrame, QvdError, QvdFileReader, QvdFileWriter, QvdIOError, QvdParseError, QvdSecurityError, QvdSymbol, QvdValidationError };
2885
+ export { QvdColumn, QvdColumnTable, QvdCorruptedError, QvdDataFrame, QvdError, QvdFileReader, QvdFileWriter, QvdIOError, QvdParseError, QvdSecurityError, QvdSymbol, QvdValidationError };
2307
2886
  //# sourceMappingURL=index.js.map
2308
2887
  //# sourceMappingURL=index.js.map