* Lazy Versioning Check, Conditional SSE Entry Fetch, HEAD Request Optimization * revert Reverted the conditional versioning check to always check versioning status Reverted the conditional SSE entry fetch to always fetch entry metadata Reverted the conditional versioning check to always check versioning status Reverted the conditional SSE entry fetch to always fetch entry metadata * Lazy Entry Fetch for SSE, Skip Conditional Header Check * SSE-KMS headers are present, this is not an SSE-C request (mutually exclusive) * SSE-C is mutually exclusive with SSE-S3 and SSE-KMS * refactor * Removed Premature Mutual Exclusivity Check * check for the presence of the X-Amz-Server-Side-Encryption header * not used * fmt * directly read write volume servers * HTTP Range Request Support * set header * md5 * copy object * fix sse * fmt * implement sse * sse continue * fixed the suffix range bug (bytes=-N for "last N bytes") * debug logs * Missing PartsCount Header * profiling * url encoding * test_multipart_get_part * headers * debug * adjust log level * handle part number * Update s3api_object_handlers.go * nil safety * set ModifiedTsNs * remove * nil check * fix sse header * same logic as filer * decode values * decode ivBase64 * s3: Fix SSE decryption JWT authentication and streaming errors Critical fix for SSE (Server-Side Encryption) test failures: 1. **JWT Authentication Bug** (Root Cause): - Changed from GenJwtForFilerServer to GenJwtForVolumeServer - S3 API now uses correct JWT when directly reading from volume servers - Matches filer's authentication pattern for direct volume access - Fixes 'unexpected EOF' and 500 errors in SSE tests 2. **Streaming Error Handling**: - Added error propagation in getEncryptedStreamFromVolumes goroutine - Use CloseWithError() to properly communicate stream failures - Added debug logging for streaming errors 3. **Response Header Timing**: - Removed premature WriteHeader(http.StatusOK) call - Let Go's http package write status automatically on first write - Prevents header lock when errors occur during streaming 4. **Enhanced SSE Decryption Debugging**: - Added IV/Key validation and logging for SSE-C, SSE-KMS, SSE-S3 - Better error messages for missing or invalid encryption metadata - Added glog.V(2) debugging for decryption setup This fixes SSE integration test failures where encrypted objects could not be retrieved due to volume server authentication failures. The JWT bug was causing volume servers to reject requests, resulting in truncated/empty streams (EOF) or internal errors. * s3: Fix SSE multipart upload metadata preservation Critical fix for SSE multipart upload test failures (SSE-C and SSE-KMS): **Root Cause - Incomplete SSE Metadata Copying**: The old code only tried to copy 'SeaweedFSSSEKMSKey' from the first part to the completed object. This had TWO bugs: 1. **Wrong Constant Name** (Key Mismatch Bug): - Storage uses: SeaweedFSSSEKMSKeyHeader = 'X-SeaweedFS-SSE-KMS-Key' - Old code read: SeaweedFSSSEKMSKey = 'x-seaweedfs-sse-kms-key' - Result: SSE-KMS metadata was NEVER copied → 500 errors 2. **Missing SSE-C and SSE-S3 Headers**: - SSE-C requires: IV, Algorithm, KeyMD5 - SSE-S3 requires: encrypted key data + standard headers - Old code: copied nothing for SSE-C/SSE-S3 → decryption failures **Fix - Complete SSE Header Preservation**: Now copies ALL SSE headers from first part to completed object: - SSE-C: SeaweedFSSSEIV, CustomerAlgorithm, CustomerKeyMD5 - SSE-KMS: SeaweedFSSSEKMSKeyHeader, AwsKmsKeyId, ServerSideEncryption - SSE-S3: SeaweedFSSSES3Key, ServerSideEncryption Applied consistently to all 3 code paths: 1. Versioned buckets (creates version file) 2. Suspended versioning (creates main object with null versionId) 3. Non-versioned buckets (creates main object) **Why This Is Correct**: The headers copied EXACTLY match what putToFiler stores during part upload (lines 496-521 in s3api_object_handlers_put.go). This ensures detectPrimarySSEType() can correctly identify encrypted multipart objects and trigger inline decryption with proper metadata. Fixes: TestSSEMultipartUploadIntegration (SSE-C and SSE-KMS subtests) * s3: Add debug logging for versioning state diagnosis Temporary debug logging to diagnose test_versioning_obj_plain_null_version_overwrite_suspended failure. Added glog.V(0) logging to show: 1. setBucketVersioningStatus: when versioning status is changed 2. PutObjectHandler: what versioning state is detected (Enabled/Suspended/none) 3. PutObjectHandler: which code path is taken (putVersionedObject vs putSuspendedVersioningObject) This will help identify if: - The versioning status is being set correctly in bucket config - The cache is returning stale/incorrect versioning state - The switch statement is correctly routing to suspended vs enabled handlers * s3: Enhanced versioning state tracing for suspended versioning diagnosis Added comprehensive logging across the entire versioning state flow: PutBucketVersioningHandler: - Log requested status (Enabled/Suspended) - Log when calling setBucketVersioningStatus - Log success/failure of status change setBucketVersioningStatus: - Log bucket and status being set - Log when config is updated - Log completion with error code updateBucketConfig: - Log versioning state being written to cache - Immediate cache verification after Set - Log if cache verification fails getVersioningState: - Log bucket name and state being returned - Log if object lock forces VersioningEnabled - Log errors This will reveal: 1. If PutBucketVersioning(Suspended) is reaching the handler 2. If the cache update succeeds 3. What state getVersioningState returns during PUT 4. Any cache consistency issues Expected to show why bucket still reports 'Enabled' after 'Suspended' call. * s3: Add SSE chunk detection debugging for multipart uploads Added comprehensive logging to diagnose why TestSSEMultipartUploadIntegration fails: detectPrimarySSEType now logs: 1. Total chunk count and extended header count 2. All extended headers with 'sse'/'SSE'/'encryption' in the name 3. For each chunk: index, SseType, and whether it has metadata 4. Final SSE type counts (SSE-C, SSE-KMS, SSE-S3) This will reveal if: - Chunks are missing SSE metadata after multipart completion - Extended headers are copied correctly from first part - The SSE detection logic is working correctly Expected to show if chunks have SseType=0 (none) or proper SSE types set. * s3: Trace SSE chunk metadata through multipart completion and retrieval Added end-to-end logging to track SSE chunk metadata lifecycle: **During Multipart Completion (filer_multipart.go)**: 1. Log finalParts chunks BEFORE mkFile - shows SseType and metadata 2. Log versionEntry.Chunks INSIDE mkFile callback - shows if mkFile preserves SSE info 3. Log success after mkFile completes **During GET Retrieval (s3api_object_handlers.go)**: 1. Log retrieved entry chunks - shows SseType and metadata after retrieval 2. Log detected SSE type result This will reveal at which point SSE chunk metadata is lost: - If finalParts have SSE metadata but versionEntry.Chunks don't → mkFile bug - If versionEntry.Chunks have SSE metadata but retrieved chunks don't → storage/retrieval bug - If chunks never have SSE metadata → multipart completion SSE processing bug Expected to show chunks with SseType=NONE during retrieval even though they were created with proper SseType during multipart completion. * s3: Fix SSE-C multipart IV base64 decoding bug **Critical Bug Found**: SSE-C multipart uploads were failing because: Root Cause: - entry.Extended[SeaweedFSSSEIV] stores base64-encoded IV (24 bytes for 16-byte IV) - SerializeSSECMetadata expects raw IV bytes (16 bytes) - During multipart completion, we were passing base64 IV directly → serialization error Error Message: "Failed to serialize SSE-C metadata for chunk in part X: invalid IV length: expected 16 bytes, got 24" Fix: - Base64-decode IV before passing to SerializeSSECMetadata - Added error handling for decode failures Impact: - SSE-C multipart uploads will now correctly serialize chunk metadata - Chunks will have proper SSE metadata for decryption during GET This fixes the SSE-C subtest of TestSSEMultipartUploadIntegration. SSE-KMS still has a separate issue (error code 23) being investigated. * fixes * kms sse * handle retry if not found in .versions folder and should read the normal object * quick check (no retries) to see if the .versions/ directory exists * skip retry if object is not found * explicit update to avoid sync delay * fix map update lock * Remove fmt.Printf debug statements * Fix SSE-KMS multipart base IV fallback to fail instead of regenerating * fmt * Fix ACL grants storage logic * header handling * nil handling * range read for sse content * test range requests for sse objects * fmt * unused code * upload in chunks * header case * fix url * bucket policy error vs bucket not found * jwt handling * fmt * jwt in request header * Optimize Case-Insensitive Prefix Check * dead code * Eliminated Unnecessary Stream Prefetch for Multipart SSE * range sse * sse * refactor * context * fmt * fix type * fix SSE-C IV Mismatch * Fix Headers Being Set After WriteHeader * fix url parsing * propergate sse headers * multipart sse-s3 * aws sig v4 authen * sse kms * set content range * better errors * Update s3api_object_handlers_copy.go * Update s3api_object_handlers.go * Update s3api_object_handlers.go * avoid magic number * clean up * Update s3api_bucket_policy_handlers.go * fix url parsing * context * data and metadata both use background context * adjust the offset * SSE Range Request IV Calculation * adjust logs * IV relative to offset in each part, not the whole file * collect logs * offset * fix offset * fix url * logs * variable * jwt * Multipart ETag semantics: conditionally set object-level Md5 for single-chunk uploads only. * sse * adjust IV and offset * multipart boundaries * ensures PUT and GET operations return consistent ETags * Metadata Header Case * CommonPrefixes Sorting with URL Encoding * always sort * remove the extra PathUnescape call * fix the multipart get part ETag * the FileChunk is created without setting ModifiedTsNs * Sort CommonPrefixes lexicographically to match AWS S3 behavior * set md5 for multipart uploads * prevents any potential data loss or corruption in the small-file inline storage path * compiles correctly * decryptedReader will now be properly closed after use * Fixed URL encoding and sort order for CommonPrefixes * Update s3api_object_handlers_list.go * SSE-x Chunk View Decryption * Different IV offset calculations for single-part vs multipart objects * still too verbose in logs * less logs * ensure correct conversion * fix listing * nil check * minor fixes * nil check * single character delimiter * optimize * range on empty object or zero-length * correct IV based on its position within that part, not its position in the entire object * adjust offset * offset Fetch FULL encrypted chunk (not just the range) Adjust IV by PartOffset/ChunkOffset only Decrypt full chunk Skip in the DECRYPTED stream to reach OffsetInChunk * look breaking * refactor * error on no content * handle intra-block byte skipping * Incomplete HTTP Response Error Handling * multipart SSE * Update s3api_object_handlers.go * address comments * less logs * handling directory * Optimized rejectDirectoryObjectWithoutSlash() to avoid unnecessary lookups * Revert "handling directory" This reverts commit 3a335f0ac33c63f51975abc63c40e5328857a74b. * constant * Consolidate nil entry checks in GetObjectHandler * add range tests * Consolidate redundant nil entry checks in HeadObjectHandler * adjust logs * SSE type * large files * large files Reverted the plain-object range test * ErrNoEncryptionConfig * Fixed SSERangeReader Infinite Loop Vulnerability * Fixed SSE-KMS Multipart ChunkReader HTTP Body Leak * handle empty directory in S3, added PyArrow tests * purge unused code * Update s3_parquet_test.py * Update requirements.txt * According to S3 specifications, when both partNumber and Range are present, the Range should apply within the selected part's boundaries, not to the full object. * handle errors * errors after writing header * https * fix: Wait for volume assignment readiness before running Parquet tests The test-implicit-dir-with-server test was failing with an Internal Error because volume assignment was not ready when tests started. This fix adds a check that attempts a volume assignment and waits for it to succeed before proceeding with tests. This ensures that: 1. Volume servers are registered with the master 2. Volume growth is triggered if needed 3. The system can successfully assign volumes for writes Fixes the timeout issue where boto3 would retry 4 times and fail with 'We encountered an internal error, please try again.' * sse tests * store derived IV * fix: Clean up gRPC ports between tests to prevent port conflicts The second test (test-implicit-dir-with-server) was failing because the volume server's gRPC port (18080 = VOLUME_PORT + 10000) was still in use from the first test. The cleanup code only killed HTTP port processes, not gRPC port processes. Added cleanup for gRPC ports in all stop targets: - Master gRPC: MASTER_PORT + 10000 (19333) - Volume gRPC: VOLUME_PORT + 10000 (18080) - Filer gRPC: FILER_PORT + 10000 (18888) This ensures clean state between test runs in CI. * add import * address comments * docs: Add placeholder documentation files for Parquet test suite Added three missing documentation files referenced in test/s3/parquet/README.md: 1. TEST_COVERAGE.md - Documents 43 total test cases (17 Go unit tests, 6 Python integration tests, 20 Python end-to-end tests) 2. FINAL_ROOT_CAUSE_ANALYSIS.md - Explains the s3fs compatibility issue with PyArrow, the implicit directory problem, and how the fix works 3. MINIO_DIRECTORY_HANDLING.md - Compares MinIO's directory handling approach with SeaweedFS's implementation Each file contains: - Title and overview - Key technical details relevant to the topic - TODO sections for future expansion These placeholder files resolve the broken README links and provide structure for future detailed documentation. * clean up if metadata operation failed * Update s3_parquet_test.py * clean up * Update Makefile * Update s3_parquet_test.py * Update Makefile * Handle ivSkip for non-block-aligned offsets * Update README.md * stop volume server faster * stop volume server in 1 second * different IV for each chunk in SSE-S3 and SSE-KMS * clean up if fails * testing upload * error propagation * fmt * simplify * fix copying * less logs * endian * Added marshaling error handling * handling invalid ranges * error handling for adding to log buffer * fix logging * avoid returning too quickly and ensure proper cleaning up * Activity Tracking for Disk Reads * Cleanup Unused Parameters * Activity Tracking for Kafka Publishers * Proper Test Error Reporting * refactoring * less logs * less logs * go fmt * guard it with if entry.Attributes.TtlSec > 0 to match the pattern used elsewhere. * Handle bucket-default encryption config errors explicitly for multipart * consistent activity tracking * obsolete code for s3 on filer read/write handlers * Update weed/s3api/s3api_object_handlers_list.go Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
422 lines
14 KiB
Python
Executable File
422 lines
14 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Test script for S3-compatible storage with PyArrow Parquet files.
|
|
|
|
This script tests different write methods (PyArrow write_dataset vs. pq.write_table to buffer)
|
|
combined with different read methods (PyArrow dataset, direct s3fs read, buffered read) to
|
|
identify which combinations work with large files that span multiple row groups.
|
|
|
|
This test specifically addresses issues with large tables using PyArrow where files span
|
|
multiple row-groups (default row_group size is around 130,000 rows).
|
|
|
|
Requirements:
|
|
- pyarrow>=22
|
|
- s3fs>=2024.12.0
|
|
|
|
Environment Variables:
|
|
S3_ENDPOINT_URL: S3 endpoint (default: http://localhost:8333)
|
|
S3_ACCESS_KEY: S3 access key (default: some_access_key1)
|
|
S3_SECRET_KEY: S3 secret key (default: some_secret_key1)
|
|
BUCKET_NAME: S3 bucket name (default: test-parquet-bucket)
|
|
TEST_QUICK: Run only small/quick tests (default: 0, set to 1 for quick mode)
|
|
|
|
Usage:
|
|
# Run with default environment variables
|
|
python3 s3_parquet_test.py
|
|
|
|
# Run with custom environment variables
|
|
S3_ENDPOINT_URL=http://localhost:8333 \
|
|
S3_ACCESS_KEY=mykey \
|
|
S3_SECRET_KEY=mysecret \
|
|
BUCKET_NAME=mybucket \
|
|
python3 s3_parquet_test.py
|
|
"""
|
|
|
|
import io
|
|
import logging
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import traceback
|
|
from datetime import datetime
|
|
from typing import Tuple
|
|
|
|
import pyarrow as pa
|
|
import pyarrow.dataset as pads
|
|
import pyarrow.parquet as pq
|
|
|
|
try:
|
|
import s3fs
|
|
except ImportError:
|
|
logging.error("s3fs not installed. Install with: pip install s3fs")
|
|
sys.exit(1)
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
|
|
|
# Error log file
|
|
ERROR_LOG_FILE = f"s3_parquet_test_errors_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
|
|
|
# Configuration from environment variables with defaults
|
|
S3_ENDPOINT_URL = os.environ.get("S3_ENDPOINT_URL", "http://localhost:8333")
|
|
S3_ACCESS_KEY = os.environ.get("S3_ACCESS_KEY", "some_access_key1")
|
|
S3_SECRET_KEY = os.environ.get("S3_SECRET_KEY", "some_secret_key1")
|
|
BUCKET_NAME = os.getenv("BUCKET_NAME", "test-parquet-bucket")
|
|
TEST_QUICK = os.getenv("TEST_QUICK", "0") == "1"
|
|
|
|
# Create randomized test directory
|
|
TEST_RUN_ID = secrets.token_hex(8)
|
|
TEST_DIR = f"{BUCKET_NAME}/parquet-tests/{TEST_RUN_ID}"
|
|
|
|
# Test file sizes
|
|
TEST_SIZES = {
|
|
"small": 5,
|
|
"large": 200_000, # This will create multiple row groups
|
|
}
|
|
|
|
# Filter to only small tests if quick mode is enabled
|
|
if TEST_QUICK:
|
|
TEST_SIZES = {"small": TEST_SIZES["small"]}
|
|
logging.info("Quick test mode enabled - running only small tests")
|
|
|
|
|
|
def create_sample_table(num_rows: int = 5) -> pa.Table:
|
|
"""Create a sample PyArrow table for testing."""
|
|
return pa.table({
|
|
"id": pa.array(range(num_rows), type=pa.int64()),
|
|
"name": pa.array([f"user_{i}" for i in range(num_rows)], type=pa.string()),
|
|
"value": pa.array([float(i) * 1.5 for i in range(num_rows)], type=pa.float64()),
|
|
"flag": pa.array([i % 2 == 0 for i in range(num_rows)], type=pa.bool_()),
|
|
})
|
|
|
|
|
|
def log_error(operation: str, short_msg: str) -> None:
|
|
"""Log error details to file with full traceback."""
|
|
with open(ERROR_LOG_FILE, "a") as f:
|
|
f.write(f"\n{'='*80}\n")
|
|
f.write(f"Operation: {operation}\n")
|
|
f.write(f"Time: {datetime.now().isoformat()}\n")
|
|
f.write(f"Message: {short_msg}\n")
|
|
f.write("Full Traceback:\n")
|
|
f.write(traceback.format_exc())
|
|
f.write(f"{'='*80}\n")
|
|
|
|
|
|
def init_s3fs() -> s3fs.S3FileSystem:
|
|
"""Initialize and return S3FileSystem."""
|
|
logging.info("Initializing S3FileSystem...")
|
|
logging.info(f" Endpoint: {S3_ENDPOINT_URL}")
|
|
logging.info(f" Bucket: {BUCKET_NAME}")
|
|
try:
|
|
fs = s3fs.S3FileSystem(
|
|
client_kwargs={"endpoint_url": S3_ENDPOINT_URL},
|
|
key=S3_ACCESS_KEY,
|
|
secret=S3_SECRET_KEY,
|
|
use_listings_cache=False,
|
|
)
|
|
logging.info("✓ S3FileSystem initialized successfully\n")
|
|
return fs
|
|
except Exception:
|
|
logging.exception("✗ Failed to initialize S3FileSystem")
|
|
raise
|
|
|
|
|
|
def ensure_bucket_exists(fs: s3fs.S3FileSystem) -> None:
|
|
"""Ensure the test bucket exists."""
|
|
try:
|
|
if not fs.exists(BUCKET_NAME):
|
|
logging.info(f"Creating bucket: {BUCKET_NAME}")
|
|
fs.mkdir(BUCKET_NAME)
|
|
logging.info(f"✓ Bucket created: {BUCKET_NAME}")
|
|
else:
|
|
logging.info(f"✓ Bucket exists: {BUCKET_NAME}")
|
|
except Exception:
|
|
logging.exception("✗ Failed to create/check bucket")
|
|
raise
|
|
|
|
|
|
# Write Methods
|
|
|
|
def write_with_pads(table: pa.Table, path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str]:
|
|
"""Write using pads.write_dataset with filesystem parameter."""
|
|
try:
|
|
pads.write_dataset(table, path, format="parquet", filesystem=fs)
|
|
return True, "pads.write_dataset"
|
|
except Exception as e:
|
|
error_msg = f"pads.write_dataset: {type(e).__name__}"
|
|
log_error("write_with_pads", error_msg)
|
|
return False, error_msg
|
|
|
|
|
|
def write_with_buffer_and_s3fs(table: pa.Table, path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str]:
|
|
"""Write using pq.write_table to buffer, then upload via s3fs."""
|
|
try:
|
|
buffer = io.BytesIO()
|
|
pq.write_table(table, buffer)
|
|
buffer.seek(0)
|
|
with fs.open(path, "wb") as f:
|
|
f.write(buffer.read())
|
|
return True, "pq.write_table+s3fs.open"
|
|
except Exception as e:
|
|
error_msg = f"pq.write_table+s3fs.open: {type(e).__name__}"
|
|
log_error("write_with_buffer_and_s3fs", error_msg)
|
|
return False, error_msg
|
|
|
|
|
|
# Read Methods
|
|
|
|
def get_parquet_files(path: str, fs: s3fs.S3FileSystem) -> list:
|
|
"""
|
|
Helper to discover all parquet files for a given path.
|
|
|
|
Args:
|
|
path: S3 path (file or directory)
|
|
fs: S3FileSystem instance
|
|
|
|
Returns:
|
|
List of parquet file paths
|
|
|
|
Raises:
|
|
ValueError: If no parquet files are found in a directory
|
|
"""
|
|
if fs.isdir(path):
|
|
# Find all parquet files in the directory
|
|
files = [f for f in fs.ls(path) if f.endswith('.parquet')]
|
|
if not files:
|
|
raise ValueError(f"No parquet files found in directory: {path}")
|
|
return files
|
|
else:
|
|
# Single file path
|
|
return [path]
|
|
|
|
|
|
def read_with_pads_dataset(path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str, int]:
|
|
"""Read using pads.dataset - handles both single files and directories."""
|
|
try:
|
|
# pads.dataset() should auto-discover parquet files in the directory
|
|
dataset = pads.dataset(path, format="parquet", filesystem=fs)
|
|
result = dataset.to_table()
|
|
return True, "pads.dataset", result.num_rows
|
|
except Exception as e:
|
|
error_msg = f"pads.dataset: {type(e).__name__}"
|
|
log_error("read_with_pads_dataset", error_msg)
|
|
return False, error_msg, 0
|
|
|
|
|
|
def read_direct_s3fs(path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str, int]:
|
|
"""Read directly via s3fs.open() streaming."""
|
|
try:
|
|
# Get all parquet files (handles both single file and directory)
|
|
parquet_files = get_parquet_files(path, fs)
|
|
|
|
# Read all parquet files and concatenate them
|
|
tables = []
|
|
for file_path in parquet_files:
|
|
with fs.open(file_path, "rb") as f:
|
|
table = pq.read_table(f)
|
|
tables.append(table)
|
|
|
|
# Concatenate all tables into one
|
|
if len(tables) == 1:
|
|
result = tables[0]
|
|
else:
|
|
result = pa.concat_tables(tables)
|
|
|
|
return True, "s3fs.open+pq.read_table", result.num_rows
|
|
except Exception as e:
|
|
error_msg = f"s3fs.open+pq.read_table: {type(e).__name__}"
|
|
log_error("read_direct_s3fs", error_msg)
|
|
return False, error_msg, 0
|
|
|
|
|
|
def read_buffered_s3fs(path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str, int]:
|
|
"""Read via s3fs.open() into buffer, then pq.read_table."""
|
|
try:
|
|
# Get all parquet files (handles both single file and directory)
|
|
parquet_files = get_parquet_files(path, fs)
|
|
|
|
# Read all parquet files and concatenate them
|
|
tables = []
|
|
for file_path in parquet_files:
|
|
with fs.open(file_path, "rb") as f:
|
|
buffer = io.BytesIO(f.read())
|
|
buffer.seek(0)
|
|
table = pq.read_table(buffer)
|
|
tables.append(table)
|
|
|
|
# Concatenate all tables into one
|
|
if len(tables) == 1:
|
|
result = tables[0]
|
|
else:
|
|
result = pa.concat_tables(tables)
|
|
|
|
return True, "s3fs.open+BytesIO+pq.read_table", result.num_rows
|
|
except Exception as e:
|
|
error_msg = f"s3fs.open+BytesIO+pq.read_table: {type(e).__name__}"
|
|
log_error("read_buffered_s3fs", error_msg)
|
|
return False, error_msg, 0
|
|
|
|
|
|
def read_with_parquet_dataset(path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str, int]:
|
|
"""Read using pq.ParquetDataset - designed for directories."""
|
|
try:
|
|
# ParquetDataset is specifically designed to handle directories
|
|
dataset = pq.ParquetDataset(path, filesystem=fs)
|
|
result = dataset.read()
|
|
return True, "pq.ParquetDataset", result.num_rows
|
|
except Exception as e:
|
|
error_msg = f"pq.ParquetDataset: {type(e).__name__}"
|
|
log_error("read_with_parquet_dataset", error_msg)
|
|
return False, error_msg, 0
|
|
|
|
|
|
def read_with_pq_read_table(path: str, fs: s3fs.S3FileSystem) -> Tuple[bool, str, int]:
|
|
"""Read using pq.read_table with filesystem parameter."""
|
|
try:
|
|
# pq.read_table() with filesystem should handle directories
|
|
result = pq.read_table(path, filesystem=fs)
|
|
return True, "pq.read_table+filesystem", result.num_rows
|
|
except Exception as e:
|
|
error_msg = f"pq.read_table+filesystem: {type(e).__name__}"
|
|
log_error("read_with_pq_read_table", error_msg)
|
|
return False, error_msg, 0
|
|
|
|
|
|
def test_combination(
|
|
fs: s3fs.S3FileSystem,
|
|
test_name: str,
|
|
write_func,
|
|
read_func,
|
|
num_rows: int,
|
|
) -> Tuple[bool, str]:
|
|
"""Test a specific write/read combination."""
|
|
table = create_sample_table(num_rows=num_rows)
|
|
path = f"{TEST_DIR}/{test_name}/data.parquet"
|
|
|
|
# Write
|
|
write_ok, write_msg = write_func(table, path, fs)
|
|
if not write_ok:
|
|
return False, f"WRITE_FAIL: {write_msg}"
|
|
|
|
# Read
|
|
read_ok, read_msg, rows_read = read_func(path, fs)
|
|
if not read_ok:
|
|
return False, f"READ_FAIL: {read_msg}"
|
|
|
|
# Verify
|
|
if rows_read != num_rows:
|
|
return False, f"DATA_MISMATCH: expected {num_rows}, got {rows_read}"
|
|
|
|
return True, f"{write_msg} + {read_msg}"
|
|
|
|
|
|
def cleanup_test_files(fs: s3fs.S3FileSystem) -> None:
|
|
"""Clean up test files from S3."""
|
|
try:
|
|
if fs.exists(TEST_DIR):
|
|
logging.info(f"Cleaning up test directory: {TEST_DIR}")
|
|
fs.rm(TEST_DIR, recursive=True)
|
|
logging.info("✓ Test directory cleaned up")
|
|
except Exception as e:
|
|
logging.warning(f"Failed to cleanup test directory: {e}")
|
|
|
|
|
|
def main():
|
|
"""Run all write/read method combinations."""
|
|
print("=" * 80)
|
|
print("Write/Read Method Combination Tests for S3-Compatible Storage")
|
|
print("Testing PyArrow Parquet Files with Multiple Row Groups")
|
|
if TEST_QUICK:
|
|
print("*** QUICK TEST MODE - Small files only ***")
|
|
print("=" * 80 + "\n")
|
|
|
|
print("Configuration:")
|
|
print(f" S3 Endpoint: {S3_ENDPOINT_URL}")
|
|
print(f" Bucket: {BUCKET_NAME}")
|
|
print(f" Test Directory: {TEST_DIR}")
|
|
print(f" Quick Mode: {'Yes (small files only)' if TEST_QUICK else 'No (all file sizes)'}")
|
|
print()
|
|
|
|
try:
|
|
fs = init_s3fs()
|
|
ensure_bucket_exists(fs)
|
|
except Exception as e:
|
|
print(f"Cannot proceed without S3 connection: {e}")
|
|
return 1
|
|
|
|
# Define all write methods
|
|
write_methods = [
|
|
("pads", write_with_pads),
|
|
("buffer+s3fs", write_with_buffer_and_s3fs),
|
|
]
|
|
|
|
# Define all read methods
|
|
read_methods = [
|
|
("pads.dataset", read_with_pads_dataset),
|
|
("pq.ParquetDataset", read_with_parquet_dataset),
|
|
("pq.read_table", read_with_pq_read_table),
|
|
("s3fs+direct", read_direct_s3fs),
|
|
("s3fs+buffered", read_buffered_s3fs),
|
|
]
|
|
|
|
results = []
|
|
|
|
# Test all combinations for each file size
|
|
for size_name, num_rows in TEST_SIZES.items():
|
|
print(f"\n{'='*80}")
|
|
print(f"Testing with {size_name} files ({num_rows:,} rows)")
|
|
print(f"{'='*80}\n")
|
|
print(f"{'Write Method':<20} | {'Read Method':<20} | {'Result':<40}")
|
|
print("-" * 85)
|
|
|
|
for write_name, write_func in write_methods:
|
|
for read_name, read_func in read_methods:
|
|
test_name = f"{size_name}_{write_name}_{read_name}"
|
|
success, message = test_combination(
|
|
fs, test_name, write_func, read_func, num_rows
|
|
)
|
|
results.append((test_name, success, message))
|
|
status = "✓ PASS" if success else "✗ FAIL"
|
|
print(f"{write_name:<20} | {read_name:<20} | {status}: {message[:35]}")
|
|
|
|
# Summary
|
|
print("\n" + "=" * 80)
|
|
print("SUMMARY")
|
|
print("=" * 80)
|
|
passed = sum(1 for _, success, _ in results if success)
|
|
total = len(results)
|
|
print(f"\nTotal: {passed}/{total} passed\n")
|
|
|
|
# Group results by file size
|
|
for size_name in TEST_SIZES.keys():
|
|
size_results = [r for r in results if size_name in r[0]]
|
|
size_passed = sum(1 for _, success, _ in size_results if success)
|
|
print(f"{size_name.upper()}: {size_passed}/{len(size_results)} passed")
|
|
|
|
print("\n" + "=" * 80)
|
|
if passed == total:
|
|
print("✓ ALL TESTS PASSED!")
|
|
else:
|
|
print(f"✗ {total - passed} test(s) failed")
|
|
print("\nFailing combinations:")
|
|
for name, success, message in results:
|
|
if not success:
|
|
parts = name.split("_")
|
|
size = parts[0]
|
|
write = parts[1]
|
|
read = "_".join(parts[2:])
|
|
print(f" - {size:6} | {write:15} | {read:20} -> {message[:50]}")
|
|
|
|
print("=" * 80 + "\n")
|
|
print(f"Error details logged to: {ERROR_LOG_FILE}")
|
|
print("=" * 80 + "\n")
|
|
|
|
# Cleanup
|
|
cleanup_test_files(fs)
|
|
|
|
return 0 if passed == total else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|
|
|