verifyIntegrity method

Future<WalPackVerification> verifyIntegrity()

Performs a full structural and CRC32-C integrity verification across the Superblock, Base TOC, every live chunk, and every WAL frame payload.

Implementation

Future<WalPackVerification> verifyIntegrity() => _mutex.synchronized(() {
  _ensureOpen();
  return _lockStrategy.withSharedLock(() async {
    final errors = <String>[];
    if (_hasCrossProcessLocks) {
      try {
        await _syncLocked(forceReopen: true);
      } on Object catch (error) {
        errors.add('Sync before verification failed: $error');
        return WalPackVerification(
          isValid: false,
          verifiedChunks: 0,
          verifiedWalFrames: 0,
          errors: List<String>.unmodifiable(errors),
        );
      }
    }
    var verifiedChunks = 0;
    var verifiedWalFrames = 0;

    final fileLength = await _backend.length();
    if (fileLength < superblockSize) {
      errors.add(
        'File shorter than superblock: $fileLength < $superblockSize',
      );
      return WalPackVerification(
        isValid: false,
        verifiedChunks: 0,
        verifiedWalFrames: 0,
        errors: List<String>.unmodifiable(errors),
      );
    }

    final Superblock sb;
    try {
      final sbBytes = await _backend.readAt(0, superblockSize);
      sb = decodeSuperblock(sbBytes);
      if (_options.expectedAppId != null &&
          sb.appId != _options.expectedAppId) {
        errors.add(
          'App ID mismatch: expected "${_options.expectedAppId}", '
          'found "${sb.appId}"',
        );
      }
    } on Object catch (error) {
      errors.add('Superblock check failed: $error');
      return WalPackVerification(
        isValid: false,
        verifiedChunks: 0,
        verifiedWalFrames: 0,
        errors: List<String>.unmodifiable(errors),
      );
    }

    if (sb.walStartOffset > fileLength) {
      errors.add(
        'Superblock walStartOffset (${sb.walStartOffset}) exceeds file '
        'length ($fileLength)',
      );
    } else {
      if (sb.tocLength > _options.limits.maxTocBytes) {
        errors.add(
          'Base TOC length (${sb.tocLength}) exceeds maxTocBytes '
          '(${_options.limits.maxTocBytes})',
        );
      } else if (sb.entryCount > _options.limits.maxEntryCount) {
        errors.add(
          'Base TOC entryCount (${sb.entryCount}) exceeds maxEntryCount '
          '(${_options.limits.maxEntryCount})',
        );
      } else if (sb.indexLength > _options.limits.maxBaseIndexBytes) {
        errors.add(
          'Base Index length (${sb.indexLength}) exceeds maxBaseIndexBytes '
          '(${_options.limits.maxBaseIndexBytes})',
        );
      } else if (sb.entryCount == 0 &&
          (sb.tocLength != 0 || sb.hasBaseIndex)) {
        errors.add('Non-zero tocLength or Base Index for empty entryCount');
      } else if (sb.entryCount > 0 && sb.tocLength == 0) {
        errors.add(
          'Zero tocLength for non-empty entryCount (${sb.entryCount})',
        );
      } else if (sb.entryCount > 0) {
        try {
          final headerLen = sb.walStartOffset - sb.tocOffset;
          final sectionBytes = await _backend.readAt(sb.tocOffset, headerLen);
          final tocBytes = sb.hasBaseIndex
              ? Uint8List.sublistView(sectionBytes, 0, sb.tocLength)
              : sectionBytes;
          List<ChunkMeta>? tocEntries;
          if (crc32c(tocBytes) != sb.tocCrc32) {
            errors.add('Base TOC CRC32-C mismatch');
          } else {
            tocEntries = decodeToc(
              tocBytes,
              sb.entryCount,
              limits: _options.limits,
              expectedTocOffset: sb.tocOffset,
            );
          }
          if (sb.hasBaseIndex) {
            final idxBytes = Uint8List.sublistView(
              sectionBytes,
              sb.tocLength,
            );
            if (crc32c(idxBytes) != sb.indexCrc32) {
              errors.add('Base Index CRC32-C mismatch');
            } else if (tocEntries != null) {
              decodeBaseIndex(
                idxBytes,
                tocEntries: tocEntries,
                limits: _options.limits,
              );
            }
          }
        } on Object catch (error) {
          errors.add('Base TOC/Index verification failed: $error');
        }
      }

      final scan = await scanWalTail(
        backend: _backend,
        startOffset: sb.walStartOffset,
        fileLength: fileLength,
        expectedStartSeq: sb.baseSeq + 1,
        verifyAllPayloads: true,
        limits: _options.limits,
      );
      verifiedWalFrames = scan.frames.length;
      if (scan.corruption case final corruption?) {
        errors.add(corruption);
      }
      if (scan.hadTornTail) {
        errors.add(
          'Unrecovered or corrupt WAL tail of ${scan.tornBytes} bytes '
          'at offset ${scan.validEndOffset}',
        );
      }
    }

    for (final meta in _chunks.values) {
      try {
        if (meta.offset + meta.storedLength > fileLength) {
          errors.add(
            'Chunk "${meta.key}" range [${meta.offset}, '
            '${meta.offset + meta.storedLength}) exceeds file length '
            '$fileLength',
          );
          continue;
        }
        final raw = await _readAndDecodeChunk(
          meta,
          forceVerifyChecksum: true,
        );
        if (raw.length != meta.rawLength) {
          errors.add(
            'Chunk "${meta.key}" decoded length ${raw.length} != '
            '${meta.rawLength}',
          );
          continue;
        }
        verifiedChunks++;
      } on Object catch (error) {
        errors.add('Chunk "${meta.key}" verification failed: $error');
      }
    }

    return WalPackVerification(
      isValid: errors.isEmpty,
      verifiedChunks: verifiedChunks,
      verifiedWalFrames: verifiedWalFrames,
      errors: List<String>.unmodifiable(errors),
    );
  });
});