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