MaxStorage
Client
- class odps.maxstorage.MaxStorageClient(odps: ODPS | None = None, *, account: BaseAccount | None = None, endpoint: str | None = None, project: str | None = None, schema: str | None = None, region: str | None = None, quota_name: str | None = None, tunnel_endpoint: str | None = None, user_agent: str | None = None, rest_client: RestClient | None = None, api_version: str = '2')[源代码]
Entry point for the MaxCompute Storage API.
Constructed from an
odps.Odpsentry (reusesRestClient+ account) or standalone with explicit account/endpoint.- 参数:
odps (ODPS, optional) -- The ODPS entry object. If given, the account/endpoint/project are derived from it.
account (Account, optional) -- Explicit account (when
odpsis not given).endpoint (str, optional) -- Storage/tunnel endpoint override.
project (str, optional) -- Default project.
schema (str, optional) -- Default schema.
region (str, optional) -- Region name for V4 signing.
quota_name (str, optional) -- Quota name for resource management.
tunnel_endpoint (str, optional) -- Tunnel endpoint override (bypasses discovery).
user_agent (str, optional) -- Custom user agent string.
rest_client (RestClient, optional) -- Pre-configured RestClient (bypasses endpoint discovery).
api_version (str, default "2") -- API version:
"2"→api/storage/v2,"3"→api/storage/v3.
- create_instance_read_session(instance, *, session_id: str | None = None, enable_limit: bool = False) InstanceReadSession[源代码]
Create (or reload via
session_id) an instance read session.- 参数:
instance (Instance or str) --
odps.models.Instanceor instance ID.session_id (str, optional) -- Reload an existing session instead of creating a new one.
enable_limit (bool, default False) -- Allow
LIMITpushdown on the instance.
示例
>>> instance = odps.execute_sql("SELECT * FROM my_table LIMIT 100") >>> session = client.create_instance_read_session(instance) >>> reader = session.open_arrow_reader(offset=0, count=100) >>> while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) >>> reader.close()
- create_table_read_session(table=None, *, descriptor: SessionDescriptor | None = None, session_id: str | None = None, columns: List[str] | None = None, partition_columns: List[str] | None = None, partitions: List[str] | None = None, bucket_ids: List[int] | None = None, split_options: SplitOptions | None = None, arrow_options: dict | None = None, filter_predicate: str | None = None, filter_predicate_fallback: bool = False, split_max_file_num: int = 0, incremental_read_options: IncrementalReadOptions | None = None, incremental_read_enabled: bool = False, session_ready_timeout: int | None = None) TableReadSession[源代码]
Create (or reload via
session_id) a table read session.Alternatively, pass
descriptorto restore a session locally from aSessionDescriptorexported elsewhere — no remote session is created or reloaded, and the descriptor is authoritative for schema, filters, incremental options, and split planning.Polls until
NORMAL(1s interval,session_ready_timeoutdefault 3600s).- 参数:
table (str or Table, optional) -- Table name or
odps.models.Table. Required unlessdescriptoris given.descriptor (SessionDescriptor, optional) -- Restore from a descriptor instead of creating a new session; supersedes
tableand every planning parameter below, and cannot be combined withtableorsession_id.session_id (str, optional) -- Reload an existing session instead of creating a new one.
partition_columns (list[str], optional) -- Partition key columns to project (read partition values as data).
partitions (list[str], optional) -- Partition specs to filter, e.g.
["pt=20230101"].bucket_ids (list[int], optional) -- Restrict reads to specific buckets of a bucketed table.
split_options (SplitOptions, optional) -- Split strategy (size, row-offset, or parallelism).
arrow_options (ArrowOptions, optional) -- Arrow read options (e.g. timestamp unit overrides).
filter_predicate (str, optional) -- Server-side filter predicate (SQL expression).
filter_predicate_fallback (bool, default False) -- Fall back to client-side filtering when the server rejects
filter_predicate.split_max_file_num (int, default 0) -- Maximum number of files per split (0 = server default).
incremental_read_options (IncrementalReadOptions, optional) -- Incremental-read configuration (mode + version range).
incremental_read_enabled (bool, default False) -- Enable incremental read for this session.
session_ready_timeout (int, optional) -- Override the default 3600s poll timeout.
示例
>>> read_session = client.create_table_read_session("my_table") >>> for split in read_session.splits: ... reader = read_session.open_arrow_reader(split) ... while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) ... reader.close()
>>> # Restore a planned session on a worker >>> descriptor = SessionDescriptor.from_json(transferred_json) >>> read_session = client.create_table_read_session(descriptor=descriptor)
- create_table_write_session(table=None, *, descriptor: SessionDescriptor | None = None, session_id: str | None = None, partition_spec: str | None = None, overwrite: bool = False, write_mode: WriteMode = WriteMode.BATCH, quota_name: str | None = None, enable_schema_evolution: bool = False, required_data_format: DataFormat | None = None, batch_compatible_options: BatchCompatibleOptions | None = None) TableWriteSession[源代码]
Create (or reload via
session_id) a table write session.Alternatively, pass
descriptorto restore a batch-compatible session locally from aSessionDescriptorexported elsewhere — no remote session is created or reloaded. The restored session is descriptor-only: it can open block writers, but commit and abort stay with the coordinator session.- 参数:
table (str or Table, optional) -- Table name or
odps.models.Table. Required unlessdescriptoris given.descriptor (SessionDescriptor, optional) -- Restore from a descriptor instead of creating a new session; supersedes
tableand every planning parameter below, and cannot be combined withtableorsession_id.session_id (str, optional) -- Reload an existing session instead of creating a new one.
partition_spec (str, optional) -- Partition to write, e.g.
"pt=20230101".overwrite (bool, default False) -- Overwrite existing data in the partition.
write_mode (WriteMode, default WriteMode.BATCH) -- Batch, batch-compatible, or streaming write mode.
required_data_format (DataFormat, optional) -- Required data format for the session (e.g.
DataFormat("Arrow", "V5")). WhenNonethe server applies its default. Forwarded as theRequiredDataFormatwire field consumed by the server.batch_compatible_options (BatchCompatibleOptions, optional) -- Advanced settings for
WriteMode.BATCH_COMPATIBLE. Ignored for other write modes.
示例
>>> import pyarrow as pa >>> write_session = client.create_table_write_session("my_table") >>> writer = write_session.open_arrow_writer(stream_id="0") >>> batch = pa.RecordBatch.from_arrays( ... [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())], ... schema=pa.schema([("id", pa.int64()), ("name", pa.string())]), ... ) >>> writer.write_batch(batch) >>> writer.close() >>> write_session.commit() >>> >>> # Batch-compatible mode >>> from odps.maxstorage import BatchCompatibleOptions, WriteMode >>> session = client.create_table_write_session( ... "my_table", ... write_mode=WriteMode.BATCH_COMPATIBLE, ... batch_compatible_options=BatchCompatibleOptions( ... enhance_write_check=True, ... ), ... ) >>> results = [] >>> for block in range(2): ... writer = session.open_block_writer(block, 0) ... root = writer.create_vector_schema_root() ... writer.write_batch(root) ... results.append(writer.commit()) >>> session.commit(block_results=results)
- open_blob_manager(table: Table | None = None) BlobManager[源代码]
Return a
BlobManagerfor standalone blob read/write.tableis optional — needed for write operations (write_blob_stream,write_blob_batch) to resolve the table identifier. Read operations (read_blobs,read_blob) do not need it.- 参数:
table (str or Table, optional) -- Table name or
odps.models.Table. Required for write operations; ignored for reads.
示例
>>> blob_manager = client.open_blob_manager("my_table") >>> records = blob_manager.read_blobs([ref1, ref2]) >>> for record in records: ... print(len(record.data))
- preview_table(table, partition_spec: str | None = None, columns: List[str] | None = None, limit: int | None = None) ArrowReader[源代码]
Preview initial rows of a table as an
ArrowReader.Uncompressed (preview sends no
ACCEPT-ENCODINGheader); for compressed reads usecreate_table_read_session+open_arrow_reader.- 参数:
示例
>>> reader = client.preview_table("my_table", limit=10) >>> while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) >>> reader.close()
- property storage_rest: RestClient
The dedicated RestClient tagged
MAXSTORAGE.
- property stub: StorageStub
The
StorageStubfor RPC operations.
Read Sessions
- class odps.maxstorage.TableReadSession(stub: StorageStub, table_id: TableIdentifier, request: CreateTableReadSessionRequest, session_id: str | None = None, session_ready_timeout: int | None = None, *, _response: CreateTableReadSessionResponse | None = None, _rows_per_split: int = 0)[源代码]
A table read session.
Created by
MaxStorageClient.create_table_read_session. After construction the session is guaranteed to be in theNORMALstatus and itssplitsare materialized.- 参数:
stub (StorageStub) -- The RPC layer.
table_id (TableIdentifier) -- Target table.
request (CreateTableReadSessionRequest) -- Creation request (partitions, split options, data format, ...).
session_id (str, optional) -- If given, reload an existing session instead of creating a new one.
session_ready_timeout (int, optional) -- Override
options.maxstorage.session_ready_timeout(default 3600s).
示例
>>> session = client.create_table_read_session("my_table") >>> for split in session.splits: ... reader = session.open_arrow_reader(split) ... while True: ... batch = reader.read() ... if batch is None: ... break ... process(batch) ... reader.close()
- property arrow_schema: pa.Schema
Arrow schema over all columns (data + partition).
- property extended_arrow_ipc_enabled: bool
Whether the session negotiated the extended Arrow IPC format.
- classmethod from_descriptor(stub: StorageStub, descriptor: SessionDescriptor) TableReadSession[源代码]
Restore a read session locally from a descriptor, without any RPC.
The descriptor is authoritative for schema, filters, incremental options, and split planning; no remote session is created or reloaded, and the supplied
stubis only used for subsequent reader calls.
- property latest_txn_id: str | None
Latest transaction id (from
LatestTxnId, used by incremental reads).
- property latest_version: int | None
Latest data version (from
LatestVersion, used by incremental reads).
- open_arrow_reader(split: IndexedInputSplit | RowRangeInputSplit, *, max_batch_rows: int = 4096, skip_row_num: int = 0, max_batch_raw_size: int = 0, data_format: DataFormat | None = None, data_columns: List[str] | None = None, data_columns_unordered: bool = False, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None, async_read: bool = False, async_queue_size: int = 2) ArrowReader[源代码]
Open an
ArrowReaderforsplit.Compression follows the tunnel pattern: pass
compress_option(aodps.tunnel.CompressOption) or the shorthandcompress_algo/compress_level. DefaultNone= uncompressed.compress_optiontakes priority over the shorthand kwargs.When compression is requested, an
ACCEPT-ENCODINGheader is sent on the stream-create request so the server compresses the Arrow stream; the reader then decompresses the response viaodps.tunnel.io.stream.get_decompress_stream().示例
>>> read_session = client.create_table_read_session("my_table") >>> for split in read_session.splits: ... reader = read_session.open_arrow_reader(split, max_batch_rows=1024) ... while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) ... reader.close() >>> >>> # Compressed read via shorthand >>> reader = read_session.open_arrow_reader( ... read_session.splits[0], compress_algo="zstd", ... ) >>> reader.close()
- property record_count: int
Total row count in this session (from
RecordCount).-1when the server does not report a record count — an absent count is unknown, not zero.
- property supported_data_formats: List[DataFormat]
List of
DataFormatsupported by this session.
- property table_schema: StorageSchema
The
ReadSchemafrom the responseDataSchema.
- to_descriptor() SessionDescriptor[源代码]
Export an immutable, credential-free description of this session.
The returned descriptor snapshots the current session state; later mutations of this session do not affect it.
- class odps.maxstorage.InstanceReadSession(stub: StorageStub, instance_id: InstanceIdentifier, request: CreateInstanceReadSessionRequest, session_id: str | None = None)[源代码]
An instance read session.
Created by
MaxStorageClient.create_instance_read_session. After construction the session is ready for reads; there is no split material and no polling.- 参数:
stub (StorageStub) -- The RPC layer.
instance_id (InstanceIdentifier) -- Target instance.
request (CreateInstanceReadSessionRequest) -- Creation request.
session_id (str, optional) -- If given, reload an existing session (
DownloadID) instead of creating a new one.
- property arrow_schema: pa.Schema
Arrow schema over all columns.
- open_arrow_reader(offset: int = 0, count: int | None = None, *, columns: List[str] | None = None, task_name: str = 'AnonymousSQLTask', query_id: int = 0, enable_limit: bool = False, compress_option: CompressOption = None, compress_algo=None, compress_level=None, async_read: bool = False, async_queue_size: int = 2) ArrowReader[源代码]
Open an
ArrowReaderfor this instance read session.task_namedefaults to"AnonymousSQLTask"and warns when unset (i.e. left at the default) to surface the likely-missing task association.Compression follows the same tunnel pattern as
TableReadSession:compress_option(defaultNone= uncompressed) or the shorthandcompress_algo/compress_level. Uncompressed is the default; LZ4 and ZSTD are also supported.示例
>>> instance = odps.execute_sql("SELECT * FROM my_table LIMIT 100") >>> session = client.create_instance_read_session(instance) >>> reader = session.open_arrow_reader(offset=0, count=100) >>> while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) >>> reader.close()
- property table_schema: StorageSchema
The
WriteSchemadeserialized fromTableSchema.
- class odps.maxstorage.IndexedInputSplit(session_id: str, split_index: int)[源代码]
A split addressed by index — used when
split_mode == SIZE.
Readers
- class odps.maxstorage.ArrowReader(raw_response, schema: StorageSchema | None, compress_option: CompressOption = None, request_id: str = '', count: int = 0, async_read: bool = False, async_queue_size: int = 2, extended: bool = False)[源代码]
Arrow reader over a Storage-API read stream.
- 参数:
raw_response (requests.Response) -- Streaming HTTP response returned by the stub's
create_*_read_stream.schema (odps.maxstorage.models.schema.StorageSchema) -- The session's table schema (
ReadSchemaorWriteSchema). Used byget_as_record_readerto buildodps.models.Recordinstances whose columns match the table schema.compress_option (odps.tunnel.CompressOption, optional) -- When set, the response stream is decompressed via
odps.tunnel.io.stream.get_decompress_stream().request_id (str, optional) -- ODPS request id captured from the stream-create response headers.
count (int, optional) -- Total number of rows available to this reader (the split's row range length, or the instance read's requested count). Defaults to
0(unknown). Exposed via thecountproperty.async_read (bool, optional) -- When
True, a background thread pre-reads Arrow batches into a bounded queue, overlapping network I/O with batch processing. DefaultFalse.async_queue_size (int, optional) -- Maximum number of batches buffered by the async reader (default 2). Larger values smooth latency spikes at the cost of memory.
extended (bool, optional) -- When
True, the response stream uses the negotiated extended Arrow IPC format: tagged substreams with metrics frames separated from table rows. Metrics collected from the stream are exposed viametrics_metadata. DefaultFalse.
示例
>>> reader = read_session.open_arrow_reader(read_session.splits[0]) >>> while True: ... batch = reader.read() ... if batch is None: ... break ... print(batch.to_pandas()) >>> reader.close()
- property arrow_schema: pa.Schema
The
pyarrow.Schemaof the underlying IPC stream.
- property count: int
Total number of rows available to this reader (set at open time).
-1when that number is unknown (the session did not report a record count and the split carries no row range).
- get_as_record_reader() ArrowRecordReader[源代码]
Return a record reader yielding
odps.models.Record.See
ArrowRecordReaderfor type-conversion and BLOB-handling details.
- get_status() str[源代码]
Return the reader status.
The Python port has no async-read lifecycle, so this is always
"OK"once the stream is openable.
- property metrics_metadata: dict | None
Metrics metadata collected from extended-IPC metrics substreams.
Nonefor ordinary (non-extended) readers; adictof merged metric key/value pairs for extended readers.
- read() pa.RecordBatch | None[源代码]
Read the next
pyarrow.RecordBatch, orNoneat EOS.
- read_next_batch() pa.RecordBatch | None[源代码]
Alias for
read(), matching the tunnel ArrowReader contract.
- property schema: StorageSchema
The session's ODPS schema — matches the tunnel ArrowReader contract.
- class odps.maxstorage.ArrowRecordReader(arrow_reader)[源代码]
Record reader over a maxstorage
ArrowReader.Subclasses the tunnel
ArrowRecordReaderso that type conversion is identical to the tunnel record reader. The only divergence is BLOB columns: the tunnel never supports them, andodps.types.validate_value()rejects theBlobtype. Here the Arrowbinaryvalue (the server-side blob reference) is stored directly asbytes, bypassing validation.
Write Sessions
- class odps.maxstorage.TableWriteSession(stub: StorageStub, table_id: TableIdentifier, *, session_id: str | None = None, partition_spec: str | None = None, overwrite: bool = False, write_mode: WriteMode = WriteMode.BATCH, quota_name: str | None = None, enable_schema_evolution: bool = False, required_data_format: DataFormat | None = None, batch_compatible_options: BatchCompatibleOptions | None = None, api_version: str = '2', _batch_compatible_response: BatchCompatibleSessionResponse | None = None)[源代码]
A write session for a MaxCompute table.
Created by
MaxStorageClient.create_table_write_session().- 参数:
stub (StorageStub) -- The RPC layer.
table_id (TableIdentifier) -- Target table.
session_id (str, optional) -- Reload an existing session instead of creating a new one.
partition_spec (str, optional) -- Partition to write, e.g.
"pt=20230101".write_mode (WriteMode, default WriteMode.BATCH) -- Batch or streaming write mode.
api_version (str, default "2") -- Storage API version (
"2"or"3").
示例
>>> import pyarrow as pa >>> session = client.create_table_write_session("my_table") >>> writer = session.open_arrow_writer(stream_id="0") >>> batch = pa.RecordBatch.from_arrays( ... [pa.array([1], pa.int64()), pa.array(["x"], pa.string())], ... schema=pa.schema([("id", pa.int64()), ("name", pa.string())]), ... ) >>> writer.write_batch(batch) >>> writer.close() >>> session.commit()
- close() None[源代码]
Auto-aborts if not committed.
Once a batch-compatible commit has been attempted, its outcome may be unknown even if the call failed; closing then performs no remote abort, and the coordinator must reconcile the session state separately. Descriptor-restored workers only close their local handle: they never abort the global session.
Either way the handle is finalized: no writer or commit is accepted afterwards, and an exported descriptor records the session as
ABORTED(abort confirmed) orUNKNOWN(outcome not observed).
- commit(stream_ids: List[str] | None = None, stream_versions: List[int] | None = None, block_results: Collection[BlockWriteResult] | None = None, wait_flying_writers_timeout_seconds: int | None = None) None[源代码]
Commit the session to finalize all uploaded data.
For
BATCH_COMPATIBLEmode, passblock_results(a collection ofBlockWriteResultfrom successful block writers). Thestream_ids/stream_versionsparameters are not used in batch-compatible mode.wait_flying_writers_timeout_seconds(batch-compatible mode only) bounds how long the server waits for in-flight writers before finalizing the commit; valid range is 1..600 seconds.Nonekeeps the server default.
- property descriptor_only: bool
Whether this session was restored from a descriptor.
Descriptor-restored sessions support block data operations only; global commit and abort stay with the coordinator session.
- classmethod from_descriptor(stub: StorageStub, descriptor: SessionDescriptor) TableWriteSession[源代码]
Restore a batch-compatible write session locally, without any RPC.
The restored session is descriptor-only: it can open block writers (which reserve quota per attempt) but cannot commit or abort the global session — those operations stay with the coordinator that created it. Closing the restored session never aborts the global session.
- property max_block_number: int | None
Exclusive block-number limit for batch-compatible sessions.
Returns
Nonefor non-batch-compatible modes or when the service omitted it. Valid block numbers are[0, max_block_number).
- open_arrow_writer(stream_id: str, stream_version: int = 1, *, buffer_size: int = 67108864, auto_upload_blobs: bool = False, blob_checksum_type=None, blob_mime_type: str | None = None, blob_custom_file_name: str | None = None, blob_metadata_callback: callable | None = None, auto_flush_enabled: bool = True, auto_close_files: bool = False, resume: bool = False, max_pending_buffers: int = 1, exactly_once_mode: bool = False, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) TableArrowWriter[源代码]
Open a
TableArrowWriterfor this session.If
resume=True, callsgetWriteStream; otherwise callscreateTableWriteStream. ReturnsTableArrowBlobUploadWriterifauto_upload_blobs, elseTableArrowWriter.Both writer classes support
get_as_record_writer()and the full blob-upload helper API (build_blob_write_item,write_blob_stream,write_blob_batch). The difference is whether BLOB cells inwrite_batch/get_as_record_writerare auto-uploaded:auto_upload_blobs=False(default): BLOB columns must already contain reference bytes — upload them yourself viawrite_blob_batchfirst and place the returned references.auto_upload_blobs=True: returns aTableArrowBlobUploadWriterthat batch-uploads rawbytes/file-like BLOB cells and replaces them with references.
- 参数:
stream_id -- write stream identifier (string).
stream_version -- write stream version (default 1).
- 关键字参数:
buffer_size -- Arrow IPC buffer size in bytes (default 64 MiB).
auto_upload_blobs -- when
True, return aTableArrowBlobUploadWriterthat auto-uploads BLOB cells inline and replaces them with references.blob_checksum_type -- checksum algorithm for blob uploads.
blob_mime_type -- session-level default MIME type, used as fallback when
blob_metadata_callbackis unset or returnsNone.blob_custom_file_name -- session-level default custom file name (API v3 only), same fallback semantics as
blob_mime_type.blob_metadata_callback -- optional callable
callback(row_index, column_name, blob_data) -> (mime_type, custom_file_name) | Noneinvoked once per inline BLOB cell.auto_flush_enabled -- whether to auto-flush when the buffer is full (default
True).auto_close_files -- when
True, the writer closes file-like objects passed to it (e.g. viawrite_batchBLOB cells orwrite_blob_batchitems) after they are consumed; objects without acloseattribute or already closed are skipped.resume -- when
True, resume an existing write stream instead of creating a new one.max_pending_buffers -- maximum number of pending async flush buffers for back-pressure (default 1).
exactly_once_mode -- enable exactly-once write semantics.
compress_option --
CompressOptionfor Arrow IPC compression.compress_algo -- shorthand for
compress_option—"zstd"/"lz4".compress_level -- compression level.
示例
>>> import pyarrow as pa >>> session = client.create_table_write_session("my_table") >>> # Plain Arrow write >>> writer = session.open_arrow_writer(stream_id="0") >>> batch = pa.RecordBatch.from_arrays( ... [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())], ... schema=pa.schema([("id", pa.int64()), ("name", pa.string())]), ... ) >>> writer.write_batch(batch) >>> writer.close() >>> session.commit() >>> >>> # Auto-upload writer: inline BLOB cells are auto-uploaded >>> writer = session.open_arrow_writer( ... stream_id="0", auto_upload_blobs=True, ... ) >>> batch = pa.RecordBatch.from_arrays( ... [pa.array([0], pa.int64()), pa.array([b"payload"], pa.binary())], ... schema=pa.schema([("id", pa.int64()), ("blob", pa.binary())]), ... ) >>> writer.write_batch(batch) >>> writer.close() >>> session.commit()
- open_block_writer(block_number: int, attempt_number: int, *, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) TableBlockWriter[源代码]
Create a
TableBlockWriterforBATCH_COMPATIBLEmode.Each call reserves a one-time upload quota for the given
block_number + attempt_numberpair. Retry the same block with a newattempt_number; do not reuse a committed or aborted writer.Compression follows the other write interfaces: pass
compress_option(aodps.tunnel.CompressOption) or the shorthandcompress_algo/compress_level. DefaultNone= uncompressed. When set, the block body is serialized as an Arrow IPC stream with the built-in codec ("zstd"/"lz4"), matchingopen_arrow_writer()— no HTTPContent-Encoding.- 参数:
block_number -- zero-based block number.
attempt_number -- zero-based attempt number for this block.
- 关键字参数:
compress_option --
CompressOptionfor Arrow IPC compression.compress_algo -- shorthand for
compress_option—"zstd"/"lz4".compress_level -- compression level.
- 抛出:
NotImplementedError -- if this session is not batch-compatible.
StorageClientError -- if the service cannot reserve quota.
Descriptor-restored sessions reject new writers once a commit has been attempted on the session or the last observed session status is no longer
NORMAL.
- to_descriptor() SessionDescriptor[源代码]
Export an immutable, credential-free description of this session.
Only
BATCH_COMPATIBLEsessions support descriptors; other write modes are rejected until their distinct recovery contracts exist.A descriptor exported after a commit was attempted cannot reopen writers on the restoring side, even when the last observed session status is still
NORMAL.
Session Descriptors
- class odps.maxstorage.SessionDescriptor(root)[源代码]
Immutable, versioned description of a storage session.
Export with a session's
to_descriptor(), serialize withto_json(), and parse on the worker withfrom_json(). Bind to a worker session throughTableReadSession.from_descriptor/TableWriteSession.from_descriptoror the matchingMaxStorageClientfactory methods. Restoration never creates or reloads a remote session; a restored write session has only block-writing authority.- classmethod create(kind, table, metadata, route_token=None, arrow=None, rows_per_split=None)[源代码]
Build a descriptor from wire-form (PascalCase) session metadata.
- 参数:
kind (SessionKind or str) -- The session purpose; a string value must equal the enum value (
"batch-read"/"incremental-read"/"batch-write").table (TableIdentifier or dict) -- Table identity (
project/table/ optionalschema).metadata (dict) -- Wire-form session metadata; unknown fields are dropped.
route_token (str, optional) -- Opaque routing token from the session response.
arrow (dict, optional) -- Write encoding units, e.g.
{"timestampUnit": "NANO", "datetimeUnit": "MILLI"}.rows_per_split (int, optional) -- Row-offset chunk size for
ROW_OFFSETread sessions.
- property kind: SessionKind
The session purpose, as a
SessionKind.
- property table_identifier
The table identity as a
TableIdentifier.
Writers
- class odps.maxstorage.TableArrowWriter(stub: StorageStub, table_id: TableIdentifier, session_id: str, stream_id: str, stream_version: int = 1, *, write_mode: WriteMode = WriteMode.BATCH, route_token: str | None = None, buffer_size: int = 67108864, auto_flush_enabled: bool = True, auto_close_files: bool = False, resume: bool = False, max_pending_buffers: int = 1, exactly_once_mode: bool = False, compress_option: CompressOption | None = None, api_version: str = '2', session: TableWriteSession | None = None)[源代码]
Arrow batch writer for a table write stream.
Caches serialized Arrow batches and flushes them as a single Arrow IPC stream body via
stub.write_table().- 参数:
stub (StorageStub) -- The RPC layer.
table_id (TableIdentifier) -- Target table.
session_id (str) -- Write session ID.
stream_id (str) -- Write stream ID (use different IDs for parallel writers).
stream_version (int, default 1) -- Write stream version.
write_mode (WriteMode, default WriteMode.BATCH) -- Batch or streaming write mode.
route_token (str, optional) -- Server routing token for session affinity.
compress_option (odps.tunnel.CompressOption, optional) -- Arrow IPC compression for write batches.
api_version (str, default "2") -- Storage API version (
"2"or"3").
示例
>>> import pyarrow as pa >>> writer = write_session.open_arrow_writer(stream_id="0") >>> batch = pa.RecordBatch.from_arrays( ... [pa.array([1, 2], pa.int64()), pa.array(["a", "b"], pa.string())], ... schema=pa.schema([("id", pa.int64()), ("name", pa.string())]), ... ) >>> writer.write_batch(batch) >>> writer.close() >>> write_session.commit()
- build_blob_write_item(data: bytes | IOBase, *, column_name: str | None = None, partition_spec: str | None = None, distribution_key: str | None = None, mime_type: str | None = None, custom_file_name: str | None = None, checksum_type=ChecksumType.NONE) BlobWriteItem[源代码]
Build a
BlobWriteItemfrom writer-resolved state.column_nameis resolved to the server-assigned column ID viaWriteSchema.find_all_blob_column_ids()(same dot-path keys). When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).partition_specaccepts the same types asPartitionSpec(str, dict, or PartitionSpec).api_versionis stamped from the writer so v3-only fields (custom_file_name) are gated automatically.示例
>>> writer = write_session.open_arrow_writer(stream_id="0") >>> items = [ ... writer.build_blob_write_item( ... b"payload", column_name="blob", mime_type="image/png", ... ) ... ]
- close() None[源代码]
Flush remaining data, then closeWriteStream.
Skips closeWriteStream when (a) streaming with session_id == "default" OR (b) stream_id == "default"; otherwise closes the stream.
The async-flush executor is always shut down (even if flush or closeWriteStream raises) so its worker thread is joined.
- flush() None[源代码]
Send all cached batches as one Arrow IPC stream body.
If an async flush is in flight, awaits and surfaces its exception first, then sync-flushes the remaining buffer.
- flush_async() Future[源代码]
Async flush using a ThreadPoolExecutor + Semaphore for backpressure.
Captures all buffer state (including
_cached_record_batchesneeded for compressed writes), submits the flush to a background worker, and retains the Future in a pending deque so failures surface from the nextwrite_batch/flush/close. The semaphore provides real backpressure: whenmax_pending_buffersflushes are in flight the nextflush_asyncblocks until one completes.Every submitted Future is tracked in
_pending_futures(not a single scalar) so thatflush(),close(), andset_row_offset()await all pending uploads, and a failure in one buffer is not erased by a success in another.On async failure the captured rows are restored to the live cache (appended after any live data to preserve submission order) so the caller can retry. Returns the Future (a completed Future when there is nothing to flush) so callers can always
.result()it.
- get_as_record_writer(row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]
Return a record-oriented writer wrapping this writer.
Returns
DeltaTableRecordWriterif an__operationcolumn is found in eithersystem_columnsorcolumns; otherwiseAppendTableRecordWriter.On a plain
TableArrowWriter, BLOB cells must already contain reference bytes. On aTableArrowBlobUploadWriter, rawbytes/ file-like values are auto-uploaded and replaced with references.- 参数:
row_count_per_batch -- rows per Arrow batch flush.
blob_batch_file_num -- max blobs per batch upload.
- set_row_offset(new_row_offset: int) None[源代码]
Flush cached data with current offset, then update (EO mode only).
Awaits any in-flight async flush first so the detached flush cannot race with the offset change and write rows at the wrong position.
- write_batch(batch) None[源代码]
Serialize a batch to Arrow IPC bytes and cache it.
batchmay be apa.Tableorpa.RecordBatch. Auto-flushes atbuffer_size.BLOB column values are sent inline as-is. To auto-upload raw
bytesand replace them with references, useTableArrowBlobUploadWriterviaauto_upload_blobs=True.
- write_blob_batch(items, *, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) WriteBlobResponse[源代码]
Batch blob upload. Returns
WriteBlobResponse.Streams frames to the server via chunked transfer-encoding — the full batch body is never materialized.
示例
>>> writer = write_session.open_arrow_writer(stream_id="0") >>> items = [ ... writer.build_blob_write_item(b"a", column_name="blob"), ... writer.build_blob_write_item(b"b", column_name="blob"), ... ] >>> resp = writer.write_blob_batch(items) >>> print(len(resp.blob_references))
- write_blob_stream(*, column_name: str | None = None, partition_spec: str | None = None, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) BlobStreamWriter[源代码]
Streaming single blob upload with MD5 verification.
Returns a
BlobStreamWriterthat streams data to the server via chunked transfer-encoding — the full blob is never materialized.column_nameis the dot-path name (a key ofWriteSchema.find_all_blob_column_ids()) resolved to the server-assigned column ID internally. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).partition_specaccepts the same types asPartitionSpec(str, dict, or PartitionSpec instance), e.g."pt=20230101"or{"pt": "20230101"}.示例
>>> writer = write_session.open_arrow_writer(stream_id="0") >>> sw = writer.write_blob_stream(column_name="blob") >>> sw.write(b"payload data") >>> resp = sw.finish() >>> print(resp.blob_reference)
- class odps.maxstorage.TableArrowBlobUploadWriter(*args, blob_checksum_type=None, blob_mime_type: str | None = None, blob_custom_file_name: str | None = None, blob_metadata_callback: callable | None = None, **kwargs)[源代码]
Arrow writer that auto-uploads BLOB cells and replaces with references.
Subclass of
TableArrowWriter.write_batchis overridden to batch-upload rawbytes/ file-like BLOB cells viatable_batch_write_bloband replace them with reference bytes before forwarding tosuper().write_batch.Use this writer when you want inline BLOB content uploaded automatically — create it via
auto_upload_blobs=TrueonTableWriteSession.open_arrow_writer().- 参数:
*args -- Forwarded to
TableArrowWriter.**kwargs -- Forwarded to
TableArrowWriter.blob_checksum_type (BlobWriteItem.ChecksumType, optional) -- Checksum algorithm for blob uploads.
blob_mime_type (str, optional) -- Session-level default MIME type for blobs.
blob_custom_file_name (str, optional) -- Session-level default custom file name (API v3 only).
blob_metadata_callback (callable, optional) --
callback(row_index, column_name, blob_data) -> (mime_type, custom_file_name) | Noneinvoked once per inline BLOB cell.
- class odps.maxstorage.TableBlockWriter(stub: StorageStub, table_id: TableIdentifier, session_id: str, block_number: int, attempt_number: int, route_token: str, quota_token: str, data_schema: BatchCompatibleDataSchema, enhance_write_check: bool, compress_option: CompressOption | None = None)[源代码]
Arrow writer for one block in
WriteMode.BATCH_COMPATIBLE.Each instance corresponds to one
block_number + attempt_numberpair. Batches are buffered in memory untilcommit()orclose()finalizes the upload as a single Arrow IPC stream.When constructed with a
compress_option, the uploaded stream uses Arrow IPC's built-in codec (zstd/lz4), matching the writer returned byopen_arrow_writer().Prefer
commit()when the returnedBlockWriteResultwill be used directly. Callingabort()discards buffered batches without creating a remote writer result; the service releases the unused quota reservation after it expires.Do not reuse a writer after it has been committed, aborted, or closed. Retry the same block with a new
attempt_number.- close() None[源代码]
Finalize the writer, uploading the block if not already done.
If
abort()was called, this is a no-op. Otherwise it uploads the buffered batches. Prefercommit()when the result is needed.
- commit() BlockWriteResult[源代码]
Finalize the block upload and return the commit result.
After
commit(), the writer is closed and cannot be reused. RaisesIOErrorif the writer was aborted.
- create_vector_schema_root() pa.Table[源代码]
Create a
pyarrow.VectorSchemaRootmatching the session schema.
- property schema: pa.Schema
The Arrow schema for this block.
- class odps.maxstorage.AppendTableRecordWriter(arrow_writer: TableArrowWriter, row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]
Row-oriented writer wrapping
TableArrowWriter.Converts Record -> Arrow batches. When the underlying writer has
auto_upload_blobs=True, BLOB columns are intercepted: file-like objects and rawbytes/bytearrayare batch-uploaded by the record writer itself and replaced with references pass through unchanged. Whenauto_upload_blobs=False, BLOB cells must already contain reference bytes.- write(record) None[源代码]
Write a single record.
Accepts
odps.types.Record,list, ortuple. BLOB columns may contain:bytes/bytearray(batch-uploaded by the record writer), file-like (streamed in chunks, never fully materialized),str(blob reference, passed through),None(null).Auto-flushes when
row_count >= row_count_per_batchor when the accumulated blob file count >=blob_batch_file_num.
- class odps.maxstorage.DeltaTableRecordWriter(arrow_writer: TableArrowWriter, row_count_per_batch: int = 1024, blob_batch_file_num: int = 1000)[源代码]
Record writer for Delta Tables (primary key tables).
write()stamps__operation='U'(UPSERT) anddelete()stamps__operation='D'(DELETE) on each record. Both operations can be freely interleaved on a single writer instance.
Write Results
- class odps.maxstorage.BlockWriteResult(session_id: str, block_number: int, attempt_number: int, record_count: int, commit_message: str)[源代码]
Result produced by a successful
TableBlockWriter.commit().The service commit message remains an implementation detail. Applications should retain or transport this object and pass it to
TableWriteSession.commit()with theblock_resultsparameter.
Blob I/O
- class odps.maxstorage.BlobManager(client: MaxStorageClient, table_id: TableIdentifier | None = None)[源代码]
Standalone blob read/write manager.
Constructed from a
MaxStorageClient; reuses itsStorageStubfor all HTTP operations.- 参数:
client (MaxStorageClient) -- The parent client.
table_id (TableIdentifier, optional) -- Table identifier — required for write operations (
write_blob_stream,write_blob_batch).
示例
>>> blob_manager = client.open_blob_manager("my_table") >>> # Read blobs by reference >>> for record in blob_manager.read_blobs([ref1, ref2]): ... print(len(record.data)) >>> # Stream a single blob >>> reader = blob_manager.read_blobs([ref], stream=True) >>> while True: ... chunk = reader.read(4096) ... if not chunk: ... break ... process(chunk)
- build_blob_write_item(data, session_id, *, column_name=None, partition_spec=None, distribution_key=None, mime_type=None, custom_file_name=None, checksum_type=ChecksumType.NONE) BlobWriteItem[源代码]
Build a
BlobWriteItemfrom writer-resolved state.column_nameis resolved to the server-assigned column ID via the write schema. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).partition_specaccepts the same types asPartitionSpec.api_versionis stamped from the client so v3-only fields are gated automatically.示例
>>> blob_manager = client.open_blob_manager("my_table") >>> write_session = client.create_table_write_session("my_table") >>> items = [ ... blob_manager.build_blob_write_item( ... b"payload", write_session.id, column_name="blob", ... mime_type="application/octet-stream", ... ) ... ]
- read_blob(blob_reference: str | bytes, *, compress_option: CompressOption | None = None, compress_algo=None) BytesIO[源代码]
Download a single blob and return a
io.BytesIOover its data.Delegates to
read_blobs()with a single-element reference list. The server returns a raw unframed stream for single-ref requests, so no frame headers are parsed. Compression follows the same pattern asread_blobs():compress_option(defaultNone= uncompressed) or the shorthandcompress_algo. The reference must be UTF-8 decodable.示例
>>> blob_manager = client.open_blob_manager() >>> bio = blob_manager.read_blob(ref) >>> data = bio.read() >>> print(len(data))
- read_blobs(blob_references: List[str | bytes], *, compress_option: CompressOption | None = None, compress_algo=None, stream: bool = False) BlobDataIterator | BlobStreamReader[源代码]
Download blobs by their references.
The server's response framing depends on the number of references:
Single reference: the server returns raw unframed blob bytes (no
[HeaderLen][Header][DataLen][Data]frames). The entire decompressed payload is yielded as oneBlobRecord.Multiple references: the server returns a framed stream with one frame per blob. Each
BlobRecordcarries the blob's MIME type and custom file name (v3+) from the frame header.
References must be UTF-8 decodable strings or bytes. Binary (non-UTF-8) references returned for nested BLOB columns are not supported by the generic
BlobReadendpoint; reading them raisesStorageClientError. Compression follows the tunnel pattern:compress_option(defaultNone= uncompressed) or the shorthandcompress_algo. Passcompress_algo="lz4"/"zstd"to request a compressed response. Whenstream=True, returns aBlobStreamReaderfor incremental file-like reads; otherwise returns aBlobDataIteratoryieldingBlobRecord.示例
>>> blob_manager = client.open_blob_manager() >>> # Materialize each blob >>> for record in blob_manager.read_blobs([ref1, ref2]): ... print(len(record.data)) >>> >>> # Incremental streaming read >>> reader = blob_manager.read_blobs([ref], stream=True) >>> while True: ... chunk = reader.read(4096) ... if not chunk: ... break ... process(chunk) ... reader = reader.next()
- write_blob_batch(items: List[BlobWriteItem], session_id: str, stream_id: str, *, stream_version: int = 1, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) WriteBlobResponse[源代码]
Batch-upload multiple blobs in one request.
Each
BlobWriteItemis framed and streamed to the server via chunked transfer-encoding — the full batch body is never materialized. Compression viacompress_option(defaultNone= uncompressed). ReturnsWriteBlobResponsewith blob_references matching input order.示例
>>> blob_manager = client.open_blob_manager("my_table") >>> write_session = client.create_table_write_session("my_table") >>> items = [ ... blob_manager.build_blob_write_item( ... b"a", write_session.id, column_name="blob", ... ), ... blob_manager.build_blob_write_item( ... b"b", write_session.id, column_name="blob", ... ), ... ] >>> resp = blob_manager.write_blob_batch( ... items, write_session.id, stream_id="0", ... ) >>> print(len(resp.blob_references))
- write_blob_stream(session_id: str, stream_id: str, *, stream_version: int = 1, column_name: str | None = None, partition_spec: str | dict | PartitionSpec | None = None, compress_option: CompressOption | None = None, compress_algo=None, compress_level=None) BlobStreamWriter[源代码]
Create a streaming writer for a single blob upload.
Uses chunked transfer-encoding; compression via
compress_option(defaultNone= uncompressed;ZSTD/LZ4_FRAMEopt-in via Content-Encoding). The returnedBlobStreamWritercomputes MD5 incrementally and verifies onfinish().column_nameis the dot-path name (a key ofWriteSchema.find_all_blob_column_ids()), resolved to the server-assigned column ID via the write schema. When omitted, the sole top-level pure-BLOB column is auto-selected (raises if the schema has multiple BLOB columns or any nested BLOB column).partition_specaccepts the same types asPartitionSpec(str, dict, or PartitionSpec).示例
>>> blob_manager = client.open_blob_manager("my_table") >>> write_session = client.create_table_write_session("my_table") >>> sw = blob_manager.write_blob_stream( ... write_session.id, stream_id="0", column_name="blob", ... ) >>> sw.write(b"payload data") >>> resp = sw.finish() >>> print(resp.blob_reference)
- class odps.maxstorage.BlobRecord(data: bytes, mime_type: str | None, custom_file_name: str | None = None)[源代码]
A single downloaded blob yielded by
BlobDataIterator.custom_file_nameis only populated when the client targets API v3+; it isNoneon v2 (theCustomFileNameheader is not parsed).
- class odps.maxstorage.BlobDataIterator(raw_stream, api_version: str = '2', expected_count: int | None = None, crc_strip: bool = True)[源代码]
Iterator yielding
BlobRecordper blob.- read_data(size: int = -1) bytes[源代码]
Read up to size bytes of the current blob's data (for BlobStreamReader).
Skip remaining_bytes of unread data and the trailing footer.
- class odps.maxstorage.BlobStreamReader(iterator: BlobDataIterator)[源代码]
File-like reader for streaming blob data from a
BlobDataIterator.Provides
read(size)for incremental reads of the current blob,mime_type/custom_file_nameproperties, and anext()method to advance to the next blob. Avoids materializing entire blobs.If
next()is called before the current blob is fully read, the reader auto-drains the remaining bytes. ReturnsNonefromnext()when no more blobs remain.- next() BlobStreamReader | None[源代码]
Advance to the next blob in-place. Returns
selforNone.
- class odps.maxstorage.BlobStreamWriter(upload: Callable, compress_option: CompressOption | None = None, api_version: str = '2')[源代码]
Stream writer for single blob upload with MD5 checksum verification.
Wraps a
RequestsIO+ compressor pipeline. Data written viawrite()is compressed (if requested) and streamed to the server in chunks via chunked transfer-encoding — the full blob is never held in memory. MD5 is computed incrementally on the uncompressed data and verified against the server response onfinish().- finish() WriteBlobResponse[源代码]
Finish writing, send the data, and verify MD5.
Returns the parsed
WriteBlobResponseon success. Raisesodps.errors.ChecksumErroron MD5 mismatch, orMaxStorageErrorif the upload fails with a non-200 response.
- class odps.maxstorage.BlobWriteItem(data, *, column_id, partition_values=None, distribution_key=None, mime_type=None, custom_file_name=None, checksum_type=ChecksumType.NONE, api_version='2')[源代码]
A single blob item for batch upload.
备注
Prefer
TableArrowWriter.build_blob_write_item()orBlobManager.build_blob_write_item()to construct items — they resolvecolumn_id, normalizepartition_spec, and stampapi_versionautomatically. ConstructingBlobWriteItemdirectly requires knowledge of server-assigned column IDs and wire-format details.
Schema and Options
- class odps.maxstorage.WriteMode(value)[源代码]
Write-session mode.
BATCH/BATCH_COMPATIBLE-- data visible only after commit.STREAMING/STREAMING_REALTIME-- data visible immediately on flush.
- class odps.maxstorage.SplitMode(value)[源代码]
Data-splitting strategy for read sessions.
JSON values:
"Size","Parallelism","RowOffset","Bucket".
- class odps.maxstorage.SplitOptions(split_mode: object = None, split_unit: str = 'ByteSize', split_number: int = 268435456, cross_partition: bool = True, bucket_sort: bool = False)[源代码]
Controls how a read session splits data.
Fields
- split_modeSplitMode
Strategy:
SIZE(default),ROW_OFFSET,PARALLELISM,BUCKET.- split_unitstr
Unit of
split_number. Default"ByteSize".- split_numberint
Target split size (bytes) for
SIZEmode, or row count forROW_OFFSET. Default 256 MiB.- cross_partitionbool
Whether splits may cross partition boundaries. Default
True.- bucket_sortbool
Whether bucket split results keep the clustered ordering. Only meaningful for
BUCKETsplits. DefaultFalse.
- class odps.maxstorage.IncrementalReadOptions(version: str | None = None, from_: int | str | None = None, to: int | str | None = None, start_txn_id: str | None = None)[源代码]
Incremental-read configuration.
Wire fields:
{Mode, From, To, StartTxnId}.versionselects the incremental mode;from_/toare version boundaries (int) or timestamps (str);start_txn_idrequests exactly-once incremental reads starting after the given transaction id.
- class odps.maxstorage.BatchCompatibleOptions(enhance_write_check: bool = False, max_field_size: int = 0, dynamic_partition_limit: int = -1)[源代码]
Immutable advanced settings for
WriteMode.BATCH_COMPATIBLE.Pass directly to
MaxStorageClient.create_table_write_session()via thebatch_compatible_optionsparameter.When unset, the server applies its own defaults.
max_field_size(if set) must be at least 1024 bytes;dynamic_partition_limituses-1to mean "server default".- classmethod create_default() BatchCompatibleOptions[源代码]
Return the default options (all server-side defaults).
- class odps.maxstorage.DataFormat(type='Arrow', version='V5')[源代码]
Arrow data-format descriptor.
JSON:
{"Type": "Arrow", "Version": "V5"}(defaults). Not anenum— it carries two free-form string fields.
Errors
- class odps.maxstorage.MaxStorageError(msg, request_id=None, code=None, host_id=None, instance_id=None, endpoint=None, tag=None, response_headers=None, status_code=None)[源代码]
Base class for all maxstorage errors.
- class odps.maxstorage.StorageServiceError(http_status, error_code=None, message=None, request_id=None)[源代码]
Server-side error.
Fields
- http_statusint
HTTP status code of the failing response.
- error_codestr
Server error code parsed from the JSON body.
- messagestr
Human-readable error message.
- request_idstr
x-odps-request-idresponse header (may beNone).