This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new a2ef00d6ee feat(bindings/python): generate ReadOptions from core 
(#9377)
a2ef00d6ee is described below

commit a2ef00d6eeed9ddd6b385f45824d8c025f61a27b
Author: Chitral Verma <[email protected]>
AuthorDate: Sun Nov 29 22:15:11 2026 +0530

    feat(bindings/python): generate ReadOptions from core (#9377)
    
    * feat(bindings/python): generate ReadOptions from core
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/python): generate ReadOptions from core
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/python): generate ReadOptions from core
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * fixup! feat(bindings/python): generate ReadOptions from core
    
    Signed-off-by: Chitral Verma <[email protected]>
    
    * docs(bindings/python): qualify the zero-prefetch chunk bound
    
    ---------
    
    Signed-off-by: Chitral Verma <[email protected]>
    Co-authored-by: Xuanwo <[email protected]>
---
 bindings/python/python/opendal/_opendal.pyi |   18 +-
 bindings/python/python/opendal/operator.pyi |   54 +-
 bindings/python/python/opendal/options.py   |  156 ++-
 bindings/python/src/operator.rs             |   54 +-
 bindings/python/src/options.rs              |  104 +-
 bindings/python/src/options/generated.rs    |  190 ++++
 dev/src/generate/options.rs                 |   42 +-
 dev/src/generate/python.rs                  | 1427 +++++++++++++++++++++++++--
 8 files changed, 1814 insertions(+), 231 deletions(-)

diff --git a/bindings/python/python/opendal/_opendal.pyi 
b/bindings/python/python/opendal/_opendal.pyi
index 3c5da5563a..51fc77d368 100644
--- a/bindings/python/python/opendal/_opendal.pyi
+++ b/bindings/python/python/opendal/_opendal.pyi
@@ -84,7 +84,23 @@ class ListOptions:
 
 @final
 class ReadOptions:
-    """Options for `read` operations."""
+    """
+    Options for read operations.
+
+    Each condition checks the file being read, and every condition must hold
+    for the read to proceed. Once the option and capability checks pass, a
+    read that reaches storage fails with `opendal.exceptions.NotFound` for a
+    missing file, no matter which conditions are set. An existing file that
+    fails a condition raises `opendal.exceptions.ConditionNotMatch`, and a
+    condition the service does not advertise through its capability raises
+    `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+    condition. A read with `size=0` validates the read
+    options and capabilities, then returns empty bytes without accessing
+    storage or evaluating conditions against the file.
+
+    See the conditional operation specification
+    for the complete cross-operation contract.
+    """
 
 @final
 class StatOptions:
diff --git a/bindings/python/python/opendal/operator.pyi 
b/bindings/python/python/opendal/operator.pyi
index dff060e52f..f14507c4d2 100644
--- a/bindings/python/python/opendal/operator.pyi
+++ b/bindings/python/python/opendal/operator.pyi
@@ -382,11 +382,19 @@ class AsyncOperator:
             If create mode (`"x"`) targets an existing file. The failure can
             surface from `write()` or `close()`.
         Unsupported
-            If the service does not support the requested write options, 
including
-            the selected checksum algorithm. Append writes cannot request a 
checksum.
+            If the service does not support the requested read or write 
options,
+            including the selected checksum algorithm. Append writes cannot 
request
+            a checksum.
         ChecksumMismatch
             If the checksum fails verification. The failure can surface from
             `write()` or `close()`.
+        OSError
+            In read mode, if reading fails, for example because the file is
+            missing or a condition fails. The failure surfaces from the file's
+            read methods, or from `seek()` when seeking from the end needs the
+            file size. With a positive `chunk` and no `size`, `open()` stats 
the
+            file first and raises such errors as `opendal.exceptions` classes
+            itself.
 
         Returns
         -------
@@ -589,17 +597,22 @@ class AsyncOperator:
         version : str, optional
             The version of the file.
         concurrent : int, optional
-            The number of concurrent readers.
+            The number of chunks to read concurrently. Has no effect without
+            `chunk`.
         chunk : int, optional
             The size of each chunk.
         gap : int, optional
-            The gap between each chunk.
+            Has no effect, because `read()` reads a single byte range.
         offset : int, optional
-            The offset of the file.
+            The byte offset to start reading from. Defaults to the start of
+            the file.
         prefetch : int, optional
-            The number of completed chunks to buffer during concurrent reads.
+            The number of completed chunks that stop counting against
+            `concurrent` while they wait to be consumed, in a read with `chunk`
+            and a `concurrent` above one.
         size : int, optional
-            The size of the file.
+            The number of bytes to read from `offset`. Defaults to the rest of
+            the file.
         if_match : str, optional
             The ETag of the file.
         if_none_match : str, optional
@@ -1152,11 +1165,19 @@ class Operator:
             If create mode (`"x"`) targets an existing file. The failure can
             surface from `write()`, `flush()`, or `close()`.
         Unsupported
-            If the service does not support the requested write options, 
including
-            the selected checksum algorithm. Append writes cannot request a 
checksum.
+            If the service does not support the requested read or write 
options,
+            including the selected checksum algorithm. Append writes cannot 
request
+            a checksum.
         ChecksumMismatch
             If the checksum fails verification. The failure can surface from
             `write()`, `flush()`, or `close()`.
+        OSError
+            In read mode, if reading fails, for example because the file is
+            missing or a condition fails. The failure surfaces from the file's
+            read methods, or from `seek()` when seeking from the end needs the
+            file size. With a positive `chunk` and no `size`, `open()` stats 
the
+            file first and raises such errors as `opendal.exceptions` classes
+            itself.
 
         Returns
         -------
@@ -1196,17 +1217,22 @@ class Operator:
         version : str, optional
             The version of the file.
         concurrent : int, optional
-            The number of concurrent readers.
+            The number of chunks to read concurrently. Has no effect without
+            `chunk`.
         chunk : int, optional
             The size of each chunk.
         gap : int, optional
-            The gap between each chunk.
+            Has no effect, because `read()` reads a single byte range.
         offset : int, optional
-            The offset of the file.
+            The byte offset to start reading from. Defaults to the start of
+            the file.
         prefetch : int, optional
-            The number of completed chunks to buffer during concurrent reads.
+            The number of completed chunks that stop counting against
+            `concurrent` while they wait to be consumed, in a read with `chunk`
+            and a `concurrent` above one.
         size : int, optional
-            The size of the file.
+            The number of bytes to read from `offset`. Defaults to the rest of
+            the file.
         if_match : str, optional
             The ETag of the file.
         if_none_match : str, optional
diff --git a/bindings/python/python/opendal/options.py 
b/bindings/python/python/opendal/options.py
index 6454e3acb4..c0489223d3 100644
--- a/bindings/python/python/opendal/options.py
+++ b/bindings/python/python/opendal/options.py
@@ -52,36 +52,154 @@ ChecksumAlgorithm: TypeAlias = Literal[
 
 
 class ReadKwargs(TypedDict, total=False):
-    """Options for `read` operations."""
+    """Options for read operations.
+
+    Each condition checks the file being read, and every condition must hold
+    for the read to proceed. Once the option and capability checks pass, a
+    read that reaches storage fails with `opendal.exceptions.NotFound` for a
+    missing file, no matter which conditions are set. An existing file that
+    fails a condition raises `opendal.exceptions.ConditionNotMatch`, and a
+    condition the service does not advertise through its capability raises
+    `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+    condition. A read with `size=0` validates the read
+    options and capabilities, then returns empty bytes without accessing
+    storage or evaluating conditions against the file.
+
+    See the conditional operation specification
+    for the complete cross-operation contract.
+    """
 
     version: str
-    """The version of the file."""
+    """Read the given version of the file instead of the current one.
+
+    This selects which stored version the read returns; it is not a
+    condition on the file. A version that does not exist raises
+    `opendal.exceptions.NotFound`.
+
+    Check `op.capability().read_with_version` before using this
+    option.
+    """
     concurrent: int
-    """The number of concurrent readers."""
+    """Set `concurrent` for the operation.
+
+    OpenDAL reads a file without concurrency by default. This is not efficient 
for cases when users
+    read large chunks of data. By setting `concurrent` together with `chunk`, 
opendal will read
+    files concurrently on supported storage services.
+
+    By setting `concurrent`, opendal will fetch chunks concurrently with
+    the given chunk size. Without `chunk`, OpenDAL does not read concurrently.
+    """
     chunk: int
-    """The size of each chunk."""
+    """Set `chunk` for the operation.
+
+    By default, OpenDAL reads the range with a single request instead of in 
chunks. Users can set chunk
+    based on their own needs.
+    `0` has the same behavior as `None`.
+
+    A read with a positive `chunk` and no `size` first
+    stats the file to learn its length.
+    That stat carries the read's version and conditions, so each of them
+    also needs its stat capability, such as
+    `op.capability().stat_with_if_modified_since` for
+    `if_modified_since`; otherwise the read raises
+    `opendal.exceptions.Unsupported`.
+    """
     gap: int
-    """The gap between each chunk."""
+    """Each call to `read()` reads a single byte range, and so does each read
+    from a file that `open()` returns, so `gap` has no effect.
+    """
     offset: int
-    """The offset of the file."""
+    """Read from this byte offset instead of from the start of the file.
+
+    An offset at or beyond the end of the file can return empty bytes or
+    raise `opendal.exceptions.RangeNotSatisfied`, depending on the service
+    and on `chunk`.
+    """
     prefetch: int
-    """The number of completed chunks to buffer during concurrent reads."""
+    """The number of completed chunks that stop counting against `concurrent`
+    while they wait to be consumed, in a read with `chunk` and a `concurrent`
+    above one.
+
+    With the default `prefetch` of `0`, such a read keeps at most `concurrent`
+    chunks in flight or waiting. Completed chunks keep their slots until
+    consumed. Once all slots are occupied, a new request starts only after
+    a chunk is consumed. A positive `prefetch` lets up to that many waiting
+    chunks free their slots, so up to `concurrent` plus `prefetch` chunks can
+    be in flight or waiting, at the cost of memory.
+
+    A positive `prefetch` cannot be combined with `content_type`,
+    `cache_control`, or `content_disposition` in `read()`. Combining them
+    raises `ValueError`.
+    """
     size: int
-    """The size of the file."""
+    """Read this many bytes from `offset`. Without `size`, the read continues 
to
+    the end of the file.
+
+    A `size` of `0` validates the other options, then returns empty bytes
+    without accessing storage. When `size` is positive, a file that ends
+    before `offset` plus `size` fails the read.
+    """
     if_match: str
-    """The ETag of the file."""
+    """Read only when the file has this exact ETag.
+
+    The condition succeeds when the file exists and its ETag equals this
+    value. A file with a different ETag raises
+    `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    `opendal.exceptions.NotFound`. Only concrete ETag values are
+    portable; a wildcard such as `"*"` has no portable meaning here.
+
+    The operation raises `opendal.exceptions.Unsupported` when the
+    service does not advertise `op.capability().read_with_if_match`.
+    """
     if_none_match: str
-    """The ETag of the file."""
+    """Read only when the file does not have this ETag.
+
+    With a concrete ETag value, the condition succeeds when the file
+    exists with a different ETag. A file whose ETag equals this value
+    raises `opendal.exceptions.ConditionNotMatch`; a missing file
+    raises `opendal.exceptions.NotFound`. Only concrete ETag values
+    are portable; a wildcard such as `"*"` has no portable meaning here.
+
+    The operation raises `opendal.exceptions.Unsupported` when the
+    service does not advertise
+    `op.capability().read_with_if_none_match`.
+    """
     if_modified_since: datetime
-    """The last modified time of the file."""
+    """Read only when the file was modified after this timestamp.
+
+    The condition succeeds when the file exists and was modified after
+    this time. A file not modified since this time raises
+    `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    `opendal.exceptions.NotFound`.
+
+    The operation raises `opendal.exceptions.Unsupported` when the
+    service does not advertise
+    `op.capability().read_with_if_modified_since`.
+    """
     if_unmodified_since: datetime
-    """The last modified time of the file."""
+    """Read only when the file was not modified after this timestamp.
+
+    The condition succeeds when the file exists and was not modified
+    after this time. A file modified after this time raises
+    `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    `opendal.exceptions.NotFound`.
+
+    The operation raises `opendal.exceptions.Unsupported` when the
+    service does not advertise
+    `op.capability().read_with_if_unmodified_since`.
+    """
     content_type: str
-    """The Content-Type response header override, where supported."""
+    """Request a `content-type` response header override from services that
+    support it, including for presigned read requests.
+    """
     cache_control: str
-    """The Cache-Control response header override, where supported."""
+    """Request a `cache-control` response header override from services that
+    support it, including for presigned read requests.
+    """
     content_disposition: str
-    """The Content-Disposition response header override, where supported."""
+    """Request a `content-disposition` response header override from services
+    that support it, including for presigned read requests.
+    """
 
 
 class WriteKwargs(TypedDict, total=False):
@@ -332,6 +450,14 @@ class OpenKwargs(ReadKwargs, WriteKwargs, total=False):
     apply only when writing, appending, or creating and raise `TypeError` in
     read mode. Use the operator's `read()` method to supply response header
     overrides.
+
+    In read mode, `open()` raises `opendal.exceptions.Unsupported` for an
+    option that the service does not support. With a positive `chunk` and
+    no `size`, `open()` first stats the file, so it also raises the
+    `opendal.exceptions` class that the read options name for a missing file
+    or a failed condition. Otherwise those errors occur later and raise
+    `OSError` from the file's read methods, or from `seek()` when seeking
+    from the end needs the file's size.
     """
 
 
diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs
index cfb8a62ab7..117978a93c 100644
--- a/bindings/python/src/operator.rs
+++ b/bindings/python/src/operator.rs
@@ -588,11 +588,19 @@ impl Operator {
     ///     If create mode (`"x"`) targets an existing file. The failure can
     ///     surface from `write()`, `flush()`, or `close()`.
     /// Unsupported
-    ///     If the service does not support the requested write options, 
including
-    ///     the selected checksum algorithm. Append writes cannot request a 
checksum.
+    ///     If the service does not support the requested read or write 
options,
+    ///     including the selected checksum algorithm. Append writes cannot 
request
+    ///     a checksum.
     /// ChecksumMismatch
     ///     If the checksum fails verification. The failure can surface from
     ///     `write()`, `flush()`, or `close()`.
+    /// OSError
+    ///     In read mode, if reading fails, for example because the file is
+    ///     missing or a condition fails. The failure surfaces from the file's
+    ///     read methods, or from `seek()` when seeking from the end needs the
+    ///     file size. With a positive `chunk` and no `size`, `open()` stats 
the
+    ///     file first and raises such errors as `opendal.exceptions` classes
+    ///     itself.
     ///
     /// Returns
     /// -------
@@ -662,17 +670,22 @@ impl Operator {
     /// version : str, optional
     ///     The version of the file.
     /// concurrent : int, optional
-    ///     The number of concurrent readers.
+    ///     The number of chunks to read concurrently. Has no effect without
+    ///     `chunk`.
     /// chunk : int, optional
     ///     The size of each chunk.
     /// gap : int, optional
-    ///     The gap between each chunk.
+    ///     Has no effect, because `read()` reads a single byte range.
     /// offset : int, optional
-    ///     The offset of the file.
+    ///     The byte offset to start reading from. Defaults to the start of
+    ///     the file.
     /// prefetch : int, optional
-    ///     The number of completed chunks to buffer during concurrent reads.
+    ///     The number of completed chunks that stop counting against
+    ///     `concurrent` while they wait to be consumed, in a read with `chunk`
+    ///     and a `concurrent` above one.
     /// size : int, optional
-    ///     The size of the file.
+    ///     The number of bytes to read from `offset`. Defaults to the rest of
+    ///     the file.
     /// if_match : str, optional
     ///     The ETag of the file.
     /// if_none_match : str, optional
@@ -1512,11 +1525,19 @@ impl AsyncOperator {
     ///     If create mode (`"x"`) targets an existing file. The failure can
     ///     surface from `write()` or `close()`.
     /// Unsupported
-    ///     If the service does not support the requested write options, 
including
-    ///     the selected checksum algorithm. Append writes cannot request a 
checksum.
+    ///     If the service does not support the requested read or write 
options,
+    ///     including the selected checksum algorithm. Append writes cannot 
request
+    ///     a checksum.
     /// ChecksumMismatch
     ///     If the checksum fails verification. The failure can surface from
     ///     `write()` or `close()`.
+    /// OSError
+    ///     In read mode, if reading fails, for example because the file is
+    ///     missing or a condition fails. The failure surfaces from the file's
+    ///     read methods, or from `seek()` when seeking from the end needs the
+    ///     file size. With a positive `chunk` and no `size`, `open()` stats 
the
+    ///     file first and raises such errors as `opendal.exceptions` classes
+    ///     itself.
     ///
     /// Returns
     /// -------
@@ -1589,17 +1610,22 @@ impl AsyncOperator {
     /// version : str, optional
     ///     The version of the file.
     /// concurrent : int, optional
-    ///     The number of concurrent readers.
+    ///     The number of chunks to read concurrently. Has no effect without
+    ///     `chunk`.
     /// chunk : int, optional
     ///     The size of each chunk.
     /// gap : int, optional
-    ///     The gap between each chunk.
+    ///     Has no effect, because `read()` reads a single byte range.
     /// offset : int, optional
-    ///     The offset of the file.
+    ///     The byte offset to start reading from. Defaults to the start of
+    ///     the file.
     /// prefetch : int, optional
-    ///     The number of completed chunks to buffer during concurrent reads.
+    ///     The number of completed chunks that stop counting against
+    ///     `concurrent` while they wait to be consumed, in a read with `chunk`
+    ///     and a `concurrent` above one.
     /// size : int, optional
-    ///     The size of the file.
+    ///     The number of bytes to read from `offset`. Defaults to the rest of
+    ///     the file.
     /// if_match : str, optional
     ///     The ETag of the file.
     /// if_none_match : str, optional
diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs
index d966f46a90..573e76a2cc 100644
--- a/bindings/python/src/options.rs
+++ b/bindings/python/src/options.rs
@@ -33,40 +33,6 @@ use std::collections::HashMap;
 mod generated;
 pub use generated::*;
 
-/// Options for `read` operations.
-#[pyclass(module = "opendal")]
-#[derive(Default)]
-pub struct ReadOptions {
-    /// The version of the file.
-    pub version: Option<String>,
-    /// The number of concurrent readers.
-    pub concurrent: Option<usize>,
-    /// The size of each chunk.
-    pub chunk: Option<usize>,
-    /// The gap between each chunk.
-    pub gap: Option<usize>,
-    /// The offset of the file.
-    pub offset: Option<u64>,
-    /// The number of completed chunks to buffer during concurrent reads.
-    pub prefetch: Option<usize>,
-    /// The size of the file.
-    pub size: Option<u64>,
-    /// The ETag of the file.
-    pub if_match: Option<String>,
-    /// The ETag of the file.
-    pub if_none_match: Option<String>,
-    /// The last modified time of the file.
-    pub if_modified_since: Option<jiff::Timestamp>,
-    /// The last modified time of the file.
-    pub if_unmodified_since: Option<jiff::Timestamp>,
-    /// The Content-Type response header override, where supported.
-    pub content_type: Option<String>,
-    /// The Cache-Control response header override, where supported.
-    pub cache_control: Option<String>,
-    /// The Content-Disposition response header override, where supported.
-    pub content_disposition: Option<String>,
-}
-
 fn map_exception(name: &str, err: PyErr) -> PyErr {
     PyErr::new::<PyTypeError, _>(format!("Unable to convert key: {name}. 
Error: {err}"))
 }
@@ -160,32 +126,6 @@ fn reject_unknown_kwargs(
     Ok(())
 }
 
-impl<'a, 'py> FromPyObject<'a, 'py> for ReadOptions {
-    type Error = PyErr;
-
-    fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
-        let dict = downcast_kwargs(obj)?;
-        reject_unknown_kwargs(&dict, READ_OPTION_KEYS, false)?;
-
-        Ok(Self {
-            version: extract_optional(&dict, "version")?,
-            concurrent: extract_optional(&dict, "concurrent")?,
-            chunk: extract_optional(&dict, "chunk")?,
-            gap: extract_optional(&dict, "gap")?,
-            offset: extract_optional(&dict, "offset")?,
-            prefetch: extract_optional(&dict, "prefetch")?,
-            size: extract_optional(&dict, "size")?,
-            if_match: extract_optional(&dict, "if_match")?,
-            if_none_match: extract_optional(&dict, "if_none_match")?,
-            if_modified_since: extract_optional(&dict, "if_modified_since")?,
-            if_unmodified_since: extract_optional(&dict, 
"if_unmodified_since")?,
-            content_type: extract_optional(&dict, "content_type")?,
-            cache_control: extract_optional(&dict, "cache_control")?,
-            content_disposition: extract_optional(&dict, 
"content_disposition")?,
-        })
-    }
-}
-
 impl ReadOptions {
     /// Extract reader options for `open(..., "rb")`.
     ///
@@ -193,23 +133,8 @@ impl ReadOptions {
     /// cannot forward them. Use `read()` for response header overrides.
     pub fn from_open_kwargs(dict: &pyo3::Bound<'_, PyDict>) -> PyResult<Self> {
         reject_unknown_kwargs(dict, OPEN_READ_OPTION_KEYS, true)?;
-
-        Ok(Self {
-            version: extract_optional(dict, "version")?,
-            concurrent: extract_optional(dict, "concurrent")?,
-            chunk: extract_optional(dict, "chunk")?,
-            gap: extract_optional(dict, "gap")?,
-            offset: extract_optional(dict, "offset")?,
-            prefetch: extract_optional(dict, "prefetch")?,
-            size: extract_optional(dict, "size")?,
-            if_match: extract_optional(dict, "if_match")?,
-            if_none_match: extract_optional(dict, "if_none_match")?,
-            if_modified_since: extract_optional(dict, "if_modified_since")?,
-            if_unmodified_since: extract_optional(dict, 
"if_unmodified_since")?,
-            content_type: None,
-            cache_control: None,
-            content_disposition: None,
-        })
+        // The overrides are now absent or `None`, so they stay unset.
+        dict.extract()
     }
 
     pub fn make_range(&self) -> BytesRange {
@@ -315,31 +240,6 @@ impl<'a, 'py> FromPyObject<'a, 'py> for WriteOptions {
     }
 }
 
-impl From<ReadOptions> for ocore::options::ReadOptions {
-    fn from(opts: ReadOptions) -> Self {
-        Self {
-            range: opts.make_range(),
-            version: opts.version,
-            if_match: opts.if_match,
-            if_none_match: opts.if_none_match,
-            if_modified_since: opts
-                .if_modified_since
-                .map(crate::utils::timestamp_from_jiff),
-            if_unmodified_since: opts
-                .if_unmodified_since
-                .map(crate::utils::timestamp_from_jiff),
-            content_length_hint: None,
-            concurrent: opts.concurrent.unwrap_or_default(),
-            chunk: opts.chunk,
-            gap: opts.gap,
-            override_content_type: opts.content_type,
-            override_cache_control: opts.cache_control,
-            override_content_disposition: opts.content_disposition,
-            ..Default::default()
-        }
-    }
-}
-
 impl From<ReadOptions> for ocore::options::ReaderOptions {
     fn from(opts: ReadOptions) -> Self {
         Self {
diff --git a/bindings/python/src/options/generated.rs 
b/bindings/python/src/options/generated.rs
index 315c9844c3..47b353ba2e 100644
--- a/bindings/python/src/options/generated.rs
+++ b/bindings/python/src/options/generated.rs
@@ -300,3 +300,193 @@ impl From<DeleteOptions> for 
ocore::options::DeleteOptions {
         }
     }
 }
+
+/// Options for read operations.
+///
+/// Each condition checks the file being read, and every condition must hold
+/// for the read to proceed. Once the option and capability checks pass, a
+/// read that reaches storage fails with `opendal.exceptions.NotFound` for a
+/// missing file, no matter which conditions are set. An existing file that
+/// fails a condition raises `opendal.exceptions.ConditionNotMatch`, and a
+/// condition the service does not advertise through its capability raises
+/// `opendal.exceptions.Unsupported`; OpenDAL never silently drops a
+/// condition. A read with `size=0` validates the read
+/// options and capabilities, then returns empty bytes without accessing
+/// storage or evaluating conditions against the file.
+///
+/// See the conditional operation specification
+/// for the complete cross-operation contract.
+#[pyclass(module = "opendal")]
+#[derive(Default, Debug)]
+pub struct ReadOptions {
+    /// Read the given version of the file instead of the current one.
+    ///
+    /// This selects which stored version the read returns; it is not a
+    /// condition on the file. A version that does not exist raises
+    /// `opendal.exceptions.NotFound`.
+    ///
+    /// Check `op.capability().read_with_version` before using this
+    /// option.
+    pub version: Option<String>,
+    /// Set `concurrent` for the operation.
+    ///
+    /// OpenDAL reads a file without concurrency by default. This is not 
efficient for cases when users
+    /// read large chunks of data. By setting `concurrent` together with 
`chunk`, opendal will read
+    /// files concurrently on supported storage services.
+    ///
+    /// By setting `concurrent`, opendal will fetch chunks concurrently with
+    /// the given chunk size. Without `chunk`, OpenDAL does not read 
concurrently.
+    pub concurrent: Option<usize>,
+    /// Set `chunk` for the operation.
+    ///
+    /// By default, OpenDAL reads the range with a single request instead of 
in chunks. Users can set chunk
+    /// based on their own needs.
+    /// `0` has the same behavior as `None`.
+    ///
+    /// A read with a positive `chunk` and no `size` first
+    /// stats the file to learn its length.
+    /// That stat carries the read's version and conditions, so each of them
+    /// also needs its stat capability, such as
+    /// `op.capability().stat_with_if_modified_since` for
+    /// `if_modified_since`; otherwise the read raises
+    /// `opendal.exceptions.Unsupported`.
+    pub chunk: Option<usize>,
+    /// Each call to `read()` reads a single byte range, and so does each read
+    /// from a file that `open()` returns, so `gap` has no effect.
+    pub gap: Option<usize>,
+    /// Read from this byte offset instead of from the start of the file.
+    ///
+    /// An offset at or beyond the end of the file can return empty bytes or
+    /// raise `opendal.exceptions.RangeNotSatisfied`, depending on the service
+    /// and on `chunk`.
+    pub offset: Option<u64>,
+    /// The number of completed chunks that stop counting against `concurrent`
+    /// while they wait to be consumed, in a read with `chunk` and a 
`concurrent`
+    /// above one.
+    ///
+    /// With the default `prefetch` of `0`, such a read keeps at most 
`concurrent`
+    /// chunks in flight or waiting. Completed chunks keep their slots until
+    /// consumed. Once all slots are occupied, a new request starts only after
+    /// a chunk is consumed. A positive `prefetch` lets up to that many waiting
+    /// chunks free their slots, so up to `concurrent` plus `prefetch` chunks 
can
+    /// be in flight or waiting, at the cost of memory.
+    ///
+    /// A positive `prefetch` cannot be combined with `content_type`,
+    /// `cache_control`, or `content_disposition` in `read()`. Combining them
+    /// raises `ValueError`.
+    pub prefetch: Option<usize>,
+    /// Read this many bytes from `offset`. Without `size`, the read continues 
to
+    /// the end of the file.
+    ///
+    /// A `size` of `0` validates the other options, then returns empty bytes
+    /// without accessing storage. When `size` is positive, a file that ends
+    /// before `offset` plus `size` fails the read.
+    pub size: Option<u64>,
+    /// Read only when the file has this exact ETag.
+    ///
+    /// The condition succeeds when the file exists and its ETag equals this
+    /// value. A file with a different ETag raises
+    /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    /// `opendal.exceptions.NotFound`. Only concrete ETag values are
+    /// portable; a wildcard such as `"*"` has no portable meaning here.
+    ///
+    /// The operation raises `opendal.exceptions.Unsupported` when the
+    /// service does not advertise `op.capability().read_with_if_match`.
+    pub if_match: Option<String>,
+    /// Read only when the file does not have this ETag.
+    ///
+    /// With a concrete ETag value, the condition succeeds when the file
+    /// exists with a different ETag. A file whose ETag equals this value
+    /// raises `opendal.exceptions.ConditionNotMatch`; a missing file
+    /// raises `opendal.exceptions.NotFound`. Only concrete ETag values
+    /// are portable; a wildcard such as `"*"` has no portable meaning here.
+    ///
+    /// The operation raises `opendal.exceptions.Unsupported` when the
+    /// service does not advertise
+    /// `op.capability().read_with_if_none_match`.
+    pub if_none_match: Option<String>,
+    /// Read only when the file was modified after this timestamp.
+    ///
+    /// The condition succeeds when the file exists and was modified after
+    /// this time. A file not modified since this time raises
+    /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    /// `opendal.exceptions.NotFound`.
+    ///
+    /// The operation raises `opendal.exceptions.Unsupported` when the
+    /// service does not advertise
+    /// `op.capability().read_with_if_modified_since`.
+    pub if_modified_since: Option<jiff::Timestamp>,
+    /// Read only when the file was not modified after this timestamp.
+    ///
+    /// The condition succeeds when the file exists and was not modified
+    /// after this time. A file modified after this time raises
+    /// `opendal.exceptions.ConditionNotMatch`; a missing file raises
+    /// `opendal.exceptions.NotFound`.
+    ///
+    /// The operation raises `opendal.exceptions.Unsupported` when the
+    /// service does not advertise
+    /// `op.capability().read_with_if_unmodified_since`.
+    pub if_unmodified_since: Option<jiff::Timestamp>,
+    /// Request a `content-type` response header override from services that
+    /// support it, including for presigned read requests.
+    pub content_type: Option<String>,
+    /// Request a `cache-control` response header override from services that
+    /// support it, including for presigned read requests.
+    pub cache_control: Option<String>,
+    /// Request a `content-disposition` response header override from services
+    /// that support it, including for presigned read requests.
+    pub content_disposition: Option<String>,
+}
+
+impl<'a, 'py> FromPyObject<'a, 'py> for ReadOptions {
+    type Error = PyErr;
+
+    fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
+        let dict = downcast_kwargs(obj)?;
+
+        Ok(Self {
+            version: extract_optional(&dict, "version")?,
+            concurrent: extract_optional(&dict, "concurrent")?,
+            chunk: extract_optional(&dict, "chunk")?,
+            gap: extract_optional(&dict, "gap")?,
+            offset: extract_optional(&dict, "offset")?,
+            prefetch: extract_optional(&dict, "prefetch")?,
+            size: extract_optional(&dict, "size")?,
+            if_match: extract_optional(&dict, "if_match")?,
+            if_none_match: extract_optional(&dict, "if_none_match")?,
+            if_modified_since: extract_optional(&dict, "if_modified_since")?,
+            if_unmodified_since: extract_optional(&dict, 
"if_unmodified_since")?,
+            content_type: extract_optional(&dict, "content_type")?,
+            cache_control: extract_optional(&dict, "cache_control")?,
+            content_disposition: extract_optional(&dict, 
"content_disposition")?,
+        })
+    }
+}
+
+impl From<ReadOptions> for ocore::options::ReadOptions {
+    fn from(opts: ReadOptions) -> Self {
+        Self {
+            range: opts.make_range(),
+            limit: None,
+            version: opts.version,
+            if_match: opts.if_match,
+            if_none_match: opts.if_none_match,
+            if_version_match: None,
+            if_version_not_match: None,
+            if_modified_since: opts
+                .if_modified_since
+                .map(crate::utils::timestamp_from_jiff),
+            if_unmodified_since: opts
+                .if_unmodified_since
+                .map(crate::utils::timestamp_from_jiff),
+            content_length_hint: None,
+            concurrent: opts.concurrent.unwrap_or_default(),
+            chunk: opts.chunk,
+            gap: opts.gap,
+            override_content_type: opts.content_type,
+            override_cache_control: opts.cache_control,
+            override_content_disposition: opts.content_disposition,
+            checksum: false,
+        }
+    }
+}
diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs
index 0aed517867..f2311179fa 100644
--- a/dev/src/generate/options.rs
+++ b/dev/src/generate/options.rs
@@ -194,29 +194,17 @@ mod tests {
         let options = parse(&path).unwrap();
 
         let names: Vec<&str> = options.iter().map(|o| 
o.name.as_str()).collect();
-        assert_eq!(
-            names,
-            [
-                "ReadOptions",
-                "WriteOptions",
-                "CopyOptions",
-                "RenameOptions"
-            ]
-        );
-
-        let read = &options[0];
-        assert_eq!(read.doc, "Options for `read` operations.");
-        assert_eq!(read.fields.len(), 14);
-        assert_eq!(read.fields[0].name, "version");
-        assert_eq!(read.fields[0].ty, OptionType::Str);
-        assert_eq!(read.fields[4].name, "offset");
-        assert_eq!(read.fields[4].ty, OptionType::Int);
-        assert_eq!(read.fields[9].name, "if_modified_since");
-        assert_eq!(read.fields[9].ty, OptionType::DateTime);
-        assert_eq!(read.fields[0].doc, "The version of the file.");
+        assert_eq!(names, ["WriteOptions", "CopyOptions", "RenameOptions"]);
 
-        let write = &options[1];
+        let write = &options[0];
+        assert_eq!(write.doc, "Options for `write` operations.");
         assert_eq!(write.fields.len(), 12);
+        assert_eq!(write.fields[0].name, "append");
+        assert_eq!(write.fields[0].ty, OptionType::Bool);
+        assert_eq!(write.fields[1].name, "chunk");
+        assert_eq!(write.fields[1].ty, OptionType::Int);
+        assert_eq!(write.fields[3].name, "cache_control");
+        assert_eq!(write.fields[3].ty, OptionType::Str);
         assert_eq!(write.fields[11].name, "checksum");
         assert_eq!(write.fields[11].ty, OptionType::ChecksumAlgo);
         assert_eq!(write.fields[10].name, "user_metadata");
@@ -226,7 +214,7 @@ mod tests {
             "The user metadata to set on the file."
         );
 
-        for option in [&options[2], &options[3]] {
+        for option in [&options[1], &options[2]] {
             assert!(
                 option
                     .fields
@@ -238,7 +226,8 @@ mod tests {
         }
 
         // A field doc keeps its paragraphs, which `options.py` renders as
-        // separate docstring paragraphs.
+        // separate docstring paragraphs. No hand-written struct has an
+        // `Option<u64>` or a timestamp any more, so a sample covers them.
         let options = parse_struct(&syn::parse_quote! {
             pub struct FakeOptions {
                 /// First paragraph,
@@ -246,6 +235,10 @@ mod tests {
                 ///
                 /// Second paragraph.
                 pub flag: Option<bool>,
+                /// An offset.
+                pub offset: Option<u64>,
+                /// A time.
+                pub since: Option<jiff::Timestamp>,
             }
         })
         .unwrap();
@@ -253,5 +246,8 @@ mod tests {
             options.fields[0].doc,
             "First paragraph,\ncontinued.\n\nSecond paragraph."
         );
+        assert_eq!(options.fields[1].ty, OptionType::Int);
+        assert_eq!(options.fields[1].doc, "An offset.");
+        assert_eq!(options.fields[2].ty, OptionType::DateTime);
     }
 }
diff --git a/dev/src/generate/python.rs b/dev/src/generate/python.rs
index 12820fd958..97ad87a81e 100644
--- a/dev/src/generate/python.rs
+++ b/dev/src/generate/python.rs
@@ -658,7 +658,10 @@ struct PyOptions {
     /// The keyword arguments in their Python order, each as:
     ///
     /// - the name, which is also the Rust field it sets;
-    /// - the core field it sets;
+    /// - the core field it sets: a field of the core struct of the same
+    ///   name, or `Struct::field` for a field of another core struct, which
+    ///   the generated conversion leaves out. Only `offset` and `size` set a
+    ///   `BytesRange`, and they set it together;
     /// - the kind that core field must have;
     /// - the Rust field type, which the methods in `operator.rs` build the
     ///   class with (see [`lowering`]).
@@ -666,6 +669,13 @@ struct PyOptions {
     /// A core field that no keyword argument sets is not exposed and keeps
     /// its default.
     options: &'static [(&'static str, &'static str, OptionKind, &'static str)],
+    /// Python docs that replace the core doc of a keyword argument, as
+    /// `(name, lines)`, where the core doc does not hold for Python.
+    docs: &'static [(&'static str, &'static [&'static str])],
+    /// Python wording for core text that names what Python does not expose,
+    /// as `(core, Python)`. Each core text sits within one doc line, and
+    /// generation fails once no doc of the class contains it.
+    rewrites: &'static [(&'static str, &'static str)],
 }
 
 /// The Python options classes generated from `core/core/src/types/options.rs`.
@@ -685,6 +695,8 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
             ("versions", "versions", OptionKind::Bool, "Option<bool>"),
             ("deleted", "deleted", OptionKind::Bool, "Option<bool>"),
         ],
+        docs: &[],
+        rewrites: &[],
     },
     PyOptions {
         name: "StatOptions",
@@ -739,6 +751,8 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
             ),
             ("checksum", "checksum", OptionKind::Bool, "bool"),
         ],
+        docs: &[],
+        rewrites: &[],
     },
     PyOptions {
         name: "DeleteOptions",
@@ -757,6 +771,150 @@ const GENERATED_OPTIONS: &[PyOptions] = &[
                 "Option<String>",
             ),
         ],
+        docs: &[],
+        rewrites: &[],
+    },
+    // `read` and `presign_read` convert this class to core `ReadOptions`.
+    // `open` in read mode, and `read` with a positive `prefetch`, convert it
+    // to core `ReaderOptions` instead, by hand in
+    // `bindings/python/src/options.rs`, which also adds `prefetch`.
+    PyOptions {
+        name: "ReadOptions",
+        options: &[
+            (
+                "version",
+                "version",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            (
+                "concurrent",
+                "concurrent",
+                OptionKind::Usize,
+                "Option<usize>",
+            ),
+            ("chunk", "chunk", OptionKind::OptionUsize, "Option<usize>"),
+            ("gap", "gap", OptionKind::OptionUsize, "Option<usize>"),
+            ("offset", "range", OptionKind::BytesRange, "Option<u64>"),
+            (
+                "prefetch",
+                "ReaderOptions::prefetch",
+                OptionKind::Usize,
+                "Option<usize>",
+            ),
+            ("size", "range", OptionKind::BytesRange, "Option<u64>"),
+            (
+                "if_match",
+                "if_match",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            (
+                "if_none_match",
+                "if_none_match",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            (
+                "if_modified_since",
+                "if_modified_since",
+                OptionKind::OptionTimestamp,
+                "Option<jiff::Timestamp>",
+            ),
+            (
+                "if_unmodified_since",
+                "if_unmodified_since",
+                OptionKind::OptionTimestamp,
+                "Option<jiff::Timestamp>",
+            ),
+            (
+                "content_type",
+                "override_content_type",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            (
+                "cache_control",
+                "override_cache_control",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+            (
+                "content_disposition",
+                "override_content_disposition",
+                OptionKind::OptionString,
+                "Option<String>",
+            ),
+        ],
+        // Core documents `range` in Rust range syntax, `gap` for
+        // `Reader::fetch`, which Python does not expose, and `prefetch` for
+        // the Rust `Reader`.
+        docs: &[
+            (
+                "gap",
+                &[
+                    "Each call to `read()` reads a single byte range, and so 
does each read",
+                    "from a file that `open()` returns, so `gap` has no 
effect.",
+                ],
+            ),
+            (
+                "offset",
+                &[
+                    "Read from this byte offset instead of from the start of 
the file.",
+                    "",
+                    "An offset at or beyond the end of the file can return 
empty bytes or",
+                    "raise `opendal.exceptions.RangeNotSatisfied`, depending 
on the service",
+                    "and on `chunk`.",
+                ],
+            ),
+            (
+                "prefetch",
+                &[
+                    "The number of completed chunks that stop counting against 
`concurrent`",
+                    "while they wait to be consumed, in a read with `chunk` 
and a `concurrent`",
+                    "above one.",
+                    "",
+                    "With the default `prefetch` of `0`, such a read keeps at 
most `concurrent`",
+                    "chunks in flight or waiting. Completed chunks keep their 
slots until",
+                    "consumed. Once all slots are occupied, a new request 
starts only after",
+                    "a chunk is consumed. A positive `prefetch` lets up to 
that many waiting",
+                    "chunks free their slots, so up to `concurrent` plus 
`prefetch` chunks can",
+                    "be in flight or waiting, at the cost of memory.",
+                    "",
+                    "A positive `prefetch` cannot be combined with 
`content_type`,",
+                    "`cache_control`, or `content_disposition` in `read()`. 
Combining them",
+                    "raises `ValueError`.",
+                ],
+            ),
+            (
+                "size",
+                &[
+                    "Read this many bytes from `offset`. Without `size`, the 
read continues to",
+                    "the end of the file.",
+                    "",
+                    "A `size` of `0` validates the other options, then returns 
empty bytes",
+                    "without accessing storage. When `size` is positive, a 
file that ends",
+                    "before `offset` plus `size` fails the read.",
+                ],
+            ),
+        ],
+        // Python has no `limit`, `content_length_hint`, or suffix range, and
+        // `read` returns `bytes`.
+        rewrites: &[
+            (
+                "A read with a zero limit or an empty range validates",
+                "A read with `size=0` validates",
+            ),
+            (
+                "then returns an empty buffer without accessing",
+                "then returns empty bytes without accessing",
+            ),
+            (
+                "and an open-ended or nonempty suffix range first",
+                "and no `size` first",
+            ),
+            (", unless `content_length_hint` is set.", "."),
+        ],
     },
 ];
 
@@ -788,7 +946,7 @@ struct PyClass {
 struct PyField {
     /// The keyword argument and the Rust field.
     name: &'static str,
-    /// The core field it sets.
+    /// The core field it sets, as listed in [`PyOptions::options`].
     core: &'static str,
     kind: OptionKind,
     /// The core doc comment, one entry per line.
@@ -817,6 +975,14 @@ fn lowering(
     Some(match (kind, rust_type) {
         (OptionKind::OptionString, "Option<String>") => 
(options::OptionType::Str, "", ""),
         (OptionKind::OptionUsize, "Option<usize>") => 
(options::OptionType::Int, "", ""),
+        // A count whose keyword argument defaults to `None`, such as
+        // `read(concurrent=None)`. An omitted count is `0`.
+        (OptionKind::Usize, "Option<usize>") => {
+            (options::OptionType::Int, "", ".unwrap_or_default()")
+        }
+        // `offset` or `size`. The conversion builds the range from both with
+        // `ReadOptions::make_range` in `bindings/python/src/options.rs`.
+        (OptionKind::BytesRange, "Option<u64>") => (options::OptionType::Int, 
"", ""),
         (OptionKind::OptionTimestamp, "Option<jiff::Timestamp>") => (
             options::OptionType::DateTime,
             "",
@@ -906,6 +1072,8 @@ impl PyNames {
 ///   Cargo features. The capability that the same doc names, such as
 ///   `op.capability().list_with_recursive`, is the check Python callers have.
 ///   The rest of that paragraph is joined into one line.
+/// - A paragraph that links the performance guide is dropped, because the
+///   guide covers the Rust API only.
 ///
 /// `renames` pairs each core field of the class with the keyword argument
 /// that sets it, where the two names differ.
@@ -929,7 +1097,9 @@ fn py_doc(
     for paragraph in lines.split(|line| line.is_empty()) {
         // A `returns` may end the line before the exception.
         let text = raises(&paragraph.join("\n"));
-        let paragraph: Vec<String> = if text.contains("`crate::layers::") {
+        let paragraph: Vec<String> = if text.contains(PERFORMANCE_GUIDE) {
+            Vec::new()
+        } else if text.contains("`crate::layers::") {
             let text = text.replace('\n', " ");
             let kept: Vec<&str> = sentences(&text)
                 .into_iter()
@@ -957,6 +1127,10 @@ fn py_doc(
     Ok(out)
 }
 
+/// The link target of the Rust performance guide in core docs.
+const PERFORMANCE_GUIDE: &str =
+    
"](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)";
+
 /// Split prose into sentences at a `. ` that an uppercase letter or a code
 /// span follows, so `e.g. a` and `(see below).` stay inside their sentence.
 fn sentences(text: &str) -> Vec<&str> {
@@ -1022,10 +1196,15 @@ fn raises(text: &str) -> String {
 /// - A core field listed in `renames`, like `override_content_type`, becomes
 ///   the keyword argument that sets it, like `content_type`. Other keyword
 ///   arguments keep their core names, like `start_after`.
+/// - A Rust `Some(value)`, like `Some(0)`, becomes the Python value `0`;
+///   `None` is already the Python value of an omitted option.
 fn py_code_span(code: &str, names: &PyNames, renames: &[(&str, &str)]) -> 
Option<String> {
     if let Some(&(_, python)) = renames.iter().find(|&&(core, _)| core == 
code) {
         return Some(python.to_string());
     }
+    if let Some(value) = code.strip_prefix("Some(").and_then(|v| 
v.strip_suffix(')')) {
+        return Some(value.to_string());
+    }
     let path = code.strip_prefix("crate::").unwrap_or(code);
     if let Some(name) = path.strip_prefix("Capability::") {
         return names
@@ -1056,26 +1235,46 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct], 
names: &PyNames) -> Resu
         }
     }
 
+    // `offset` and `size` both set a range, so neither renames it.
     let renames: Vec<(&str, &str)> = spec
         .options
         .iter()
-        .filter(|&&(name, core, ..)| name != core)
+        .filter(|&&(name, core, kind, _)| name != core && kind != 
OptionKind::BytesRange)
         .map(|&(name, core, ..)| (core, name))
         .collect();
+    for &(name, _) in spec.docs {
+        if !spec.options.iter().any(|&(option, ..)| option == name) {
+            bail!("Python {class} has a doc for `{name}`, which it does not 
list");
+        }
+    }
     let mut fields = Vec::with_capacity(spec.options.len());
     for &(name, core_name, kind, rust_type) in spec.options {
         if fields.iter().any(|field: &PyField| field.name == name) {
             bail!("Python {class} lists `{name}` twice");
         }
-        if fields.iter().any(|field: &PyField| field.core == core_name) {
+        if kind == OptionKind::BytesRange {
+            if !["offset", "size"].contains(&name) {
+                bail!(
+                    "Python {class}.{name} sets core `{core_name}`, a range 
that only \
+                     `offset` and `size` set"
+                );
+            }
+        } else if fields.iter().any(|field: &PyField| field.core == core_name) 
{
             bail!("Python {class} sets core `{core_name}` twice");
         }
-        let Some(field) = core.fields.iter().find(|field| field.name == 
core_name) else {
-            bail!("core {class} has no field `{core_name}` for Python 
{class}.{name}");
+        let (owner, core_field) = core_name.split_once("::").unwrap_or((class, 
core_name));
+        if owner == class && core_field != core_name {
+            bail!("Python {class}.{name} must name core `{core_field}` without 
`{class}::`");
+        }
+        let Some(owner_struct) = parsed.iter().find(|options| options.name == 
owner) else {
+            bail!("core options struct `{owner}` not found for Python 
{class}.{name}");
+        };
+        let Some(field) = owner_struct.fields.iter().find(|f| f.name == 
core_field) else {
+            bail!("core {owner} has no field `{core_field}` for Python 
{class}.{name}");
         };
         if field.kind != kind {
             bail!(
-                "core {class}::{core_name} has kind {:?}; Python 
{class}.{name} requires {kind:?}",
+                "core {owner}::{core_field} has kind {:?}; Python 
{class}.{name} requires {kind:?}",
                 field.kind
             );
         }
@@ -1085,40 +1284,77 @@ fn py_class(spec: &PyOptions, parsed: &[OptionsStruct], 
names: &PyNames) -> Resu
                  teach dev/src/generate/python.rs about it"
             );
         };
-        fields.push(PyField {
-            name,
-            core: core_name,
-            kind,
-            doc: py_doc(
+        let doc = match spec.docs.iter().find(|&&(option, _)| option == name) {
+            Some((_, doc)) => doc.iter().map(|line| 
line.to_string()).collect(),
+            None if kind == OptionKind::BytesRange => bail!(
+                "Python {class}.{name} needs a Python doc, because core 
documents \
+                 `{core_name}` in Rust range syntax"
+            ),
+            None => py_doc(
                 &field.doc,
-                &format!("{class}::{core_name}"),
+                &format!("{owner}::{core_field}"),
                 names,
                 &renames,
             )?,
+        };
+        fields.push(PyField {
+            name,
+            core: core_name,
+            kind,
+            doc,
             rust_type,
             extract,
             convert,
         });
     }
 
-    let conversion = core
-        .fields
-        .iter()
-        .map(|field| {
-            let expr = match fields.iter().find(|f| f.core == field.name) {
-                None => default_expr(field.kind).to_string(),
-                Some(f) => format!("opts.{}{}", f.name, f.convert),
-            };
-            ConvertField {
-                name: field.name.clone(),
-                expr,
+    // The rewrites change docs rendered from core, not the Python docs.
+    let mut doc = py_doc(&core.doc, class, names, &renames)?;
+    let mut unused: Vec<&str> = spec.rewrites.iter().map(|&(from, _)| 
from).collect();
+    let from_core = fields
+        .iter_mut()
+        .filter(|f| !spec.docs.iter().any(|&(name, _)| name == f.name));
+    for line in doc
+        .iter_mut()
+        .chain(from_core.flat_map(|f| f.doc.iter_mut()))
+    {
+        for &(from, to) in spec.rewrites {
+            if line.contains(from) {
+                *line = line.replace(from, to);
+                unused.retain(|&text| text != from);
             }
-        })
-        .collect();
+        }
+    }
+    if let Some(text) = unused.first() {
+        bail!(
+            "core {class} docs no longer contain `{text}`; \
+             update its Python rewrite in dev/src/generate/python.rs"
+        );
+    }
+
+    let mut conversion = Vec::with_capacity(core.fields.len());
+    for field in &core.fields {
+        let setters: Vec<&PyField> = fields.iter().filter(|f| f.core == 
field.name).collect();
+        let expr = match setters.as_slice() {
+            [] => default_expr(field.kind).to_string(),
+            [f] if f.kind != OptionKind::BytesRange => format!("opts.{}{}", 
f.name, f.convert),
+            // `make_range` in `bindings/python/src/options.rs` builds the
+            // range from `offset` and `size`, as `open` does.
+            [_, _] => "opts.make_range()".to_string(),
+            _ => bail!(
+                "Python {class} sets core `{}` with only one of `offset` and 
`size`",
+                field.name
+            ),
+        };
+        conversion.push(ConvertField {
+            name: field.name.clone(),
+            expr,
+        });
+    }
 
     Ok(PyClass {
         name: class,
-        doc: py_doc(&core.doc, class, names, &renames)?,
+        doc,
         fields,
         conversion,
     })
@@ -1254,7 +1490,7 @@ fn render_options_py(workspace_dir: &Path, generated: 
&[PyClass]) -> Result<Stri
     // TypedDict inherits both.
     exports.push("OpenKwargs".to_string());
     out.push_str(
-        "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n    
\"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n    
Accepted keys depend on `mode`: read modes (`\"r\"`, `\"rb\"`, `\"br\"`) 
accept\n    reader options only, while write, append, and create modes 
(`\"w\"`, `\"wb\"`,\n    `\"ab\"`, `\"xb\"`, etc.) accept writer options 
only.\n\n    The `content_type`, `cache_control`, and `content_disposition` 
options\n    apply only when writing, appending, [...]
+        "\n\nclass OpenKwargs(ReadKwargs, WriteKwargs, total=False):\n    
\"\"\"Keyword arguments for `Operator.open` and `AsyncOperator.open`.\n\n    
Accepted keys depend on `mode`: read modes (`\"r\"`, `\"rb\"`, `\"br\"`) 
accept\n    reader options only, while write, append, and create modes 
(`\"w\"`, `\"wb\"`,\n    `\"ab\"`, `\"xb\"`, etc.) accept writer options 
only.\n\n    The `content_type`, `cache_control`, and `content_disposition` 
options\n    apply only when writing, appending, [...]
     );
 
     out.push_str("\n\n__all__ = [\n");
@@ -1374,7 +1610,10 @@ mod tests {
     fn generated_class(parsed: &[OptionsStruct], name: &str) -> PyClass {
         let classes = generated_classes(parsed, &py_names()).unwrap();
         let names: Vec<&str> = classes.iter().map(|class| 
class.name).collect();
-        assert_eq!(names, ["ListOptions", "StatOptions", "DeleteOptions"]);
+        assert_eq!(
+            names,
+            ["ListOptions", "StatOptions", "DeleteOptions", "ReadOptions"]
+        );
         classes
             .into_iter()
             .find(|class| class.name == name)
@@ -1389,6 +1628,91 @@ mod tests {
         ("override_content_disposition", "content_disposition"),
     ];
 
+    /// The `ReadOptions` keyword arguments whose core fields have other
+    /// names, as `(core, Python)`. `offset` and `size` set core `range`
+    /// together, so they rename nothing.
+    const READ_RENAMES: [(&str, &str); 4] = [
+        ("ReaderOptions::prefetch", "prefetch"),
+        ("override_content_type", "content_type"),
+        ("override_cache_control", "cache_control"),
+        ("override_content_disposition", "content_disposition"),
+    ];
+
+    /// The Python wording of the `ReadOptions` docs for core text that names
+    /// what Python does not expose, as `(core, Python)`.
+    const READ_REWRITES: [(&str, &str); 4] = [
+        (
+            "A read with a zero limit or an empty range validates",
+            "A read with `size=0` validates",
+        ),
+        (
+            "then returns an empty buffer without accessing",
+            "then returns empty bytes without accessing",
+        ),
+        (
+            "and an open-ended or nonempty suffix range first",
+            "and no `size` first",
+        ),
+        (", unless `content_length_hint` is set.", "."),
+    ];
+
+    /// `py_doc` of a core `ReadOptions` doc, with the Python wording.
+    fn read_doc(core_doc: &[String], item: &str) -> Vec<String> {
+        py_doc(core_doc, item, &py_names(), &READ_RENAMES)
+            .unwrap()
+            .into_iter()
+            .map(|line| {
+                READ_REWRITES
+                    .iter()
+                    .fold(line, |line, (from, to)| line.replace(from, to))
+            })
+            .collect()
+    }
+
+    /// The Python docs of the `ReadOptions` keyword arguments whose core
+    /// docs do not hold for Python, as `(name, doc)`.
+    const READ_PYTHON_DOCS: [(&str, &str); 4] = [
+        (
+            "gap",
+            "Each call to `read()` reads a single byte range, and so does each 
read\n\
+             from a file that `open()` returns, so `gap` has no effect.",
+        ),
+        (
+            "offset",
+            "Read from this byte offset instead of from the start of the 
file.\n\
+             \n\
+             An offset at or beyond the end of the file can return empty bytes 
or\n\
+             raise `opendal.exceptions.RangeNotSatisfied`, depending on the 
service\n\
+             and on `chunk`.",
+        ),
+        (
+            "prefetch",
+            "The number of completed chunks that stop counting against 
`concurrent`\n\
+             while they wait to be consumed, in a read with `chunk` and a 
`concurrent`\n\
+             above one.\n\
+             \n\
+             With the default `prefetch` of `0`, such a read keeps at most 
`concurrent`\n\
+             chunks in flight or waiting. Completed chunks keep their slots 
until\n\
+             consumed. Once all slots are occupied, a new request starts only 
after\n\
+             a chunk is consumed. A positive `prefetch` lets up to that many 
waiting\n\
+             chunks free their slots, so up to `concurrent` plus `prefetch` 
chunks can\n\
+             be in flight or waiting, at the cost of memory.\n\
+             \n\
+             A positive `prefetch` cannot be combined with `content_type`,\n\
+             `cache_control`, or `content_disposition` in `read()`. Combining 
them\n\
+             raises `ValueError`.",
+        ),
+        (
+            "size",
+            "Read this many bytes from `offset`. Without `size`, the read 
continues to\n\
+             the end of the file.\n\
+             \n\
+             A `size` of `0` validates the other options, then returns empty 
bytes\n\
+             without accessing storage. When `size` is positive, a file that 
ends\n\
+             before `offset` plus `size` fails the read.",
+        ),
+    ];
+
     /// The docstrings of every class and class field in `source`, keyed by
     /// `Class` and `Class.field`, as Python's `ast` parses them and
     /// `inspect.cleandoc` dedents them. Panics when `source` is not valid
@@ -1654,6 +1978,108 @@ print(json.dumps(docs))
         }
     }
 
+    /// The `ReadOptions` surface on main (f47ec7c1f), copied from
+    /// `bindings/python/src/options.rs`, and the Python checks and exceptions
+    /// its docs name: each field's capability is the one `OpRead::check` in
+    /// `core/core/src/raw/ops.rs` enforces for it, and the exceptions are the
+    /// error kinds of each field in `core/core/src/types/options.rs`, plus
+    /// the one the Python `offset` doc names. The doc wording itself is
+    /// core's, so a core reword passes.
+    fn assert_read_surface(class: &PyClass) {
+        let fields: Vec<String> = class
+            .fields
+            .iter()
+            .map(|f| format!("{}: {}", f.name, f.rust_type))
+            .collect();
+        assert_eq!(
+            fields,
+            [
+                "version: Option<String>",
+                "concurrent: Option<usize>",
+                "chunk: Option<usize>",
+                "gap: Option<usize>",
+                "offset: Option<u64>",
+                "prefetch: Option<usize>",
+                "size: Option<u64>",
+                "if_match: Option<String>",
+                "if_none_match: Option<String>",
+                "if_modified_since: Option<jiff::Timestamp>",
+                "if_unmodified_since: Option<jiff::Timestamp>",
+                "content_type: Option<String>",
+                "cache_control: Option<String>",
+                "content_disposition: Option<String>",
+            ]
+        );
+
+        assert_eq!(
+            spans(&class.doc, "opendal.exceptions."),
+            ["NotFound", "ConditionNotMatch", "Unsupported"],
+            "{:?}",
+            class.doc
+        );
+        let references: Vec<String> = class
+            .fields
+            .iter()
+            .map(|f| {
+                format!(
+                    "{}: {} / {}",
+                    f.name,
+                    spans(&f.doc, "op.capability().").join(" "),
+                    spans(&f.doc, "opendal.exceptions.").join(" ")
+                )
+            })
+            .collect();
+        let condition = "ConditionNotMatch NotFound Unsupported";
+        assert_eq!(
+            references,
+            [
+                "version: read_with_version / NotFound".to_string(),
+                "concurrent:  / ".to_string(),
+                "chunk: stat_with_if_modified_since / Unsupported".to_string(),
+                "gap:  / ".to_string(),
+                "offset:  / RangeNotSatisfied".to_string(),
+                "prefetch:  / ".to_string(),
+                "size:  / ".to_string(),
+                format!("if_match: read_with_if_match / {condition}"),
+                format!("if_none_match: read_with_if_none_match / 
{condition}"),
+                format!("if_modified_since: read_with_if_modified_since / 
{condition}"),
+                format!("if_unmodified_since: read_with_if_unmodified_since / 
{condition}"),
+                "content_type:  / ".to_string(),
+                "cache_control:  / ".to_string(),
+                "content_disposition:  / ".to_string(),
+            ]
+        );
+
+        // No Rust-only names or Rust-only guides reach Python callers, no
+        // error kind keeps its core name, and Python raises the exceptions
+        // that core returns.
+        let exceptions = py_names().exceptions;
+        for doc in 
std::iter::once(&class.doc).chain(class.fields.iter().map(|f| &f.doc)) {
+            let text = doc.join(" ");
+            for rust in [
+                "crate::",
+                "Capability::",
+                "ErrorKind::",
+                "returns `opendal.exceptions.",
+                "`override_",
+                "`range`",
+                "Some(",
+                "Reader",
+                "BytesRange",
+                "performance guide",
+                "limit",
+                "suffix",
+                "content_length_hint",
+                "empty buffer",
+            ] {
+                assert!(!text.contains(rust), "{rust} in {text}");
+            }
+            for kind in exceptions.keys() {
+                assert!(!text.contains(&format!("`{kind}`")), "{kind} in 
{text}");
+            }
+        }
+    }
+
     /// The keyword-only parameters of every `#[pyo3(signature)]` method in
     /// `bindings/python/src/operator.rs`, keyed by type and method, each as
     /// `name=default`.
@@ -2072,31 +2498,361 @@ print(json.dumps(docs))
         assert!(rs.contains(&format!("{expected}}}\n")), "{rs}");
     }
 
-    /// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
-    /// 809b76472 for `StatKwargs`, 501c5d96f for `DeleteKwargs`): the class
-    /// order and the keys and types of the generated classes, with
-    /// docstrings taken from core.
+    /// The `ReadOptions` API on main (f47ec7c1f), copied from
+    /// `bindings/python/src/options.rs`, with docstrings taken from core
+    /// except for the keyword arguments that core documents for Rust only.
     #[test]
-    fn test_options_py_matches_main() {
-        let generated = generated_classes(&core_options(), 
&py_names()).unwrap();
-        let py = render_options_py(&crate::workspace_dir(), 
&generated).unwrap();
-        let classes: Vec<&str> = py
-            .lines()
-            .filter_map(|line| line.strip_prefix("class "))
-            .map(|class| class.split('(').next().unwrap())
-            .collect();
+    fn test_read_options_match_main() {
+        let parsed = core_options();
+        let class = generated_class(&parsed, "ReadOptions");
+        assert_read_surface(&class);
+
+        // Each docstring is the core doc comment of the field it sets, or
+        // its Python doc.
+        let core = parsed.iter().find(|o| o.name == "ReadOptions").unwrap();
+        let reader = parsed.iter().find(|o| o.name == 
"ReaderOptions").unwrap();
+        let names = py_names();
+        assert_eq!(class.doc, read_doc(&core.doc, "ReadOptions"));
+        for field in &class.fields {
+            if let Some(&(_, doc)) = READ_PYTHON_DOCS.iter().find(|&&(n, _)| n 
== field.name) {
+                assert_eq!(field.doc.join("\n"), doc, "{}", field.name);
+                continue;
+            }
+            let name = READ_RENAMES
+                .iter()
+                .find(|&&(_, python)| python == field.name)
+                .map_or(field.name, |&(core, _)| core);
+            let core = core.fields.iter().find(|f| f.name == name).unwrap();
+            assert_eq!(field.doc, read_doc(&core.doc, name), "{name}");
+        }
+        // The Python wording, as a reader sees it.
+        let text = |doc: &[String]| doc.join(" ");
+        assert!(
+            text(&class.doc).contains(
+                "A read with `size=0` validates the read options and 
capabilities, \
+                 then returns empty bytes without accessing storage or 
evaluating \
+                 conditions against the file."
+            ),
+            "{:?}",
+            class.doc
+        );
+        let chunk = class.fields.iter().find(|f| f.name == "chunk").unwrap();
+        assert!(
+            text(&chunk.doc).contains(
+                "A read with a positive `chunk` and no `size` first stats the 
file to \
+                 learn its length. That stat carries the read's version and 
conditions"
+            ),
+            "{:?}",
+            chunk.doc
+        );
+        // `prefetch` sets a field of core `ReaderOptions` and documents it.
+        let prefetch = class.fields.iter().find(|f| f.name == 
"prefetch").unwrap();
+        assert_eq!(prefetch.core, "ReaderOptions::prefetch");
+        assert!(reader.fields.iter().any(|f| f.name == "prefetch"));
+
+        // Each keyword sets the core field main's `From` impl set it to,
+        // `offset` and `size` set the range through `make_range`, an omitted
+        // `concurrent` is `0`, `prefetch` sets no `ReadOptions` field, and
+        // every other core field, such as `limit`, keeps the default that
+        // main's `..Default::default()` gave it.
+        let (set, defaulted): (Vec<_>, Vec<_>) = class
+            .conversion
+            .iter()
+            .map(|f| format!("{}: {}", f.name, f.expr))
+            .partition(|f| f.contains("opts."));
         assert_eq!(
-            classes,
+            set,
             [
-                "ReadKwargs",
-                "WriteKwargs",
-                "ListKwargs",
-                "StatKwargs",
-                "CopyKwargs",
-                "RenameKwargs",
-                "DeleteKwargs",
-                "OpenKwargs",
-            ]
+                "range: opts.make_range()",
+                "version: opts.version",
+                "if_match: opts.if_match",
+                "if_none_match: opts.if_none_match",
+                "if_modified_since: 
opts.if_modified_since.map(crate::utils::timestamp_from_jiff)",
+                "if_unmodified_since: 
opts.if_unmodified_since.map(crate::utils::timestamp_from_jiff)",
+                "concurrent: opts.concurrent.unwrap_or_default()",
+                "chunk: opts.chunk",
+                "gap: opts.gap",
+                "override_content_type: opts.content_type",
+                "override_cache_control: opts.cache_control",
+                "override_content_disposition: opts.content_disposition",
+            ]
+        );
+        for field in [
+            "limit: None",
+            "if_version_match: None",
+            "if_version_not_match: None",
+            "content_length_hint: None",
+            "checksum: false",
+        ] {
+            assert!(defaulted.contains(&field.to_string()), "{defaulted:?}");
+        }
+        for field in &defaulted {
+            let value = field.split_once(": ").unwrap().1;
+            assert!(
+                ["None", "false", "0", "Default::default()"].contains(&value),
+                "{field}"
+            );
+        }
+
+        // `FromPyObject` reads each key as main did, and any other key is
+        // ignored; `open` rejects unknown keys before it extracts.
+        let rs = render_options_rs(&generated_classes(&parsed, 
&names).unwrap()).unwrap();
+        let extract = rs
+            .split_once("impl<'a, 'py> FromPyObject<'a, 'py> for ReadOptions 
{")
+            .unwrap()
+            .1
+            .split("\n}\n")
+            .next()
+            .unwrap();
+        let reads: Vec<&str> = extract
+            .lines()
+            .map(str::trim)
+            .filter(|line| line.contains("extract_optional"))
+            .collect();
+        assert_eq!(
+            reads,
+            [
+                "version: extract_optional(&dict, \"version\")?,",
+                "concurrent: extract_optional(&dict, \"concurrent\")?,",
+                "chunk: extract_optional(&dict, \"chunk\")?,",
+                "gap: extract_optional(&dict, \"gap\")?,",
+                "offset: extract_optional(&dict, \"offset\")?,",
+                "prefetch: extract_optional(&dict, \"prefetch\")?,",
+                "size: extract_optional(&dict, \"size\")?,",
+                "if_match: extract_optional(&dict, \"if_match\")?,",
+                "if_none_match: extract_optional(&dict, \"if_none_match\")?,",
+                "if_modified_since: extract_optional(&dict, 
\"if_modified_since\")?,",
+                "if_unmodified_since: extract_optional(&dict, 
\"if_unmodified_since\")?,",
+                "content_type: extract_optional(&dict, \"content_type\")?,",
+                "cache_control: extract_optional(&dict, \"cache_control\")?,",
+                "content_disposition: extract_optional(&dict, 
\"content_disposition\")?,",
+            ]
+        );
+
+        // The doc comments, which become `__doc__` and the `_opendal.pyi`
+        // docstrings, hold every line of the docs, and the fields keep
+        // main's order.
+        let comment = |doc: &[String], indent: &str| -> String {
+            doc.iter()
+                .map(|line| match line.as_str() {
+                    "" => format!("{indent}///"),
+                    line => format!("{indent}/// {line}"),
+                })
+                .collect::<Vec<_>>()
+                .join("\n")
+        };
+        let mut expected = format!(
+            "{}\n#[pyclass(module = \"opendal\")]\n#[derive(Default, 
Debug)]\npub struct ReadOptions {{\n",
+            comment(&class.doc, "")
+        );
+        for f in &class.fields {
+            expected += &format!(
+                "{}\n    pub {}: {},\n",
+                comment(&f.doc, "    "),
+                f.name,
+                f.rust_type
+            );
+        }
+        assert!(rs.contains(&format!("{expected}}}\n")), "{rs}");
+    }
+
+    /// `open` in read mode accepts the `ReadOptions` keyword arguments
+    /// except the response header overrides, and `reject_unknown_kwargs`
+    /// treats every `ReadOptions` keyword argument as a read option. The
+    /// lists in `bindings/python/src/options.rs` match main (f47ec7c1f) and
+    /// the table.
+    #[test]
+    fn test_open_read_keys_match_main() {
+        let path = 
crate::workspace_dir().join("bindings/python/src/options.rs");
+        let file = 
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
+        let list = |name: &str| -> Vec<String> {
+            let item = file
+                .items
+                .iter()
+                .find_map(|item| match item {
+                    syn::Item::Const(c) if c.ident == name => Some(c),
+                    _ => None,
+                })
+                .unwrap_or_else(|| panic!("{name} not found"));
+            let syn::Expr::Reference(r) = &*item.expr else {
+                panic!("{name} is not a slice reference");
+            };
+            let syn::Expr::Array(array) = &*r.expr else {
+                panic!("{name} is not an array");
+            };
+            array
+                .elems
+                .iter()
+                .map(|e| match e {
+                    syn::Expr::Lit(syn::ExprLit {
+                        lit: syn::Lit::Str(s),
+                        ..
+                    }) => s.value(),
+                    _ => panic!("{name} holds a non-string"),
+                })
+                .collect()
+        };
+        let open = [
+            "version",
+            "concurrent",
+            "chunk",
+            "gap",
+            "offset",
+            "prefetch",
+            "size",
+            "if_match",
+            "if_none_match",
+            "if_modified_since",
+            "if_unmodified_since",
+        ];
+        let overrides = ["content_type", "cache_control", 
"content_disposition"];
+        assert_eq!(list("OPEN_READ_OPTION_KEYS"), open);
+        let read: Vec<&str> = open.iter().chain(&overrides).copied().collect();
+        assert_eq!(list("READ_OPTION_KEYS"), read);
+
+        let class = generated_class(&core_options(), "ReadOptions");
+        let names: Vec<&str> = class.fields.iter().map(|f| f.name).collect();
+        assert_eq!(names, read);
+        // The keys `open` rejects are the response header overrides, which
+        // core `ReaderOptions` cannot carry.
+        let overridden: Vec<&str> = class
+            .fields
+            .iter()
+            .filter(|f| f.core.starts_with("override_"))
+            .map(|f| f.name)
+            .collect();
+        assert_eq!(overridden, overrides);
+    }
+
+    /// `open` and `read` with a positive `prefetch` convert the class to
+    /// core `ReaderOptions` by hand in `bindings/python/src/options.rs`.
+    /// That conversion must set every core `ReaderOptions` field that a
+    /// keyword argument sets, so a keyword added to the table cannot be
+    /// silently dropped there. The keywords it carries match main
+    /// (f47ec7c1f): the range goes to the reader separately, and the
+    /// overrides are rejected before the conversion.
+    #[test]
+    fn test_reader_options_conversion_covers_table() {
+        let path = 
crate::workspace_dir().join("bindings/python/src/options.rs");
+        let file = 
syn::parse_file(&fs::read_to_string(path).unwrap()).unwrap();
+        let last_ident = |ty: &syn::Type| match ty {
+            syn::Type::Path(p) => p.path.segments.last().map(|s| 
s.ident.to_string()),
+            _ => None,
+        };
+        let conversion = file
+            .items
+            .iter()
+            .find_map(|item| {
+                let syn::Item::Impl(impl_) = item else {
+                    return None;
+                };
+                let (trait_, _) = impl_.trait_.as_ref()?;
+                let from = trait_.segments.last()?;
+                let syn::PathArguments::AngleBracketed(args) = &from.arguments 
else {
+                    return None;
+                };
+                let Some(syn::GenericArgument::Type(source)) = 
args.args.first() else {
+                    return None;
+                };
+                (from.ident == "From"
+                    && last_ident(source).as_deref() == Some("ReadOptions")
+                    && last_ident(&impl_.self_ty).as_deref() == 
Some("ReaderOptions"))
+                .then_some(impl_)
+            })
+            .expect("From<ReadOptions> for ReaderOptions not found");
+        let syn::ImplItem::Fn(from) = &conversion.items[0] else {
+            panic!("expected `fn from`");
+        };
+        let Some(syn::Stmt::Expr(syn::Expr::Struct(init), None)) = 
from.block.stmts.last() else {
+            panic!("expected a struct literal");
+        };
+        // Each core field and the `opts` field its value starts from, as in
+        // `opts.concurrent.unwrap_or_default()`.
+        let set: BTreeMap<String, String> = init
+            .fields
+            .iter()
+            .map(|f| {
+                let syn::Member::Named(name) = &f.member else {
+                    panic!("unnamed member");
+                };
+                let mut expr = &f.expr;
+                while let syn::Expr::MethodCall(call) = expr {
+                    expr = &call.receiver;
+                }
+                let source = match expr {
+                    syn::Expr::Field(field) => match (&*field.base, 
&field.member) {
+                        (syn::Expr::Path(base), syn::Member::Named(member))
+                            if base.path.is_ident("opts") =>
+                        {
+                            member.to_string()
+                        }
+                        _ => String::new(),
+                    },
+                    _ => String::new(),
+                };
+                (name.to_string(), source)
+            })
+            .collect();
+
+        let parsed = core_options();
+        let reader = parsed.iter().find(|o| o.name == 
"ReaderOptions").unwrap();
+        let class = generated_class(&parsed, "ReadOptions");
+        let mut carried = Vec::new();
+        for field in &class.fields {
+            let core = field
+                .core
+                .strip_prefix("ReaderOptions::")
+                .unwrap_or(field.core);
+            if !reader.fields.iter().any(|f| f.name == core) {
+                continue;
+            }
+            let source = set
+                .get(core)
+                .unwrap_or_else(|| panic!("the ReaderOptions conversion does 
not set `{core}`"));
+            assert_eq!(source, field.name, "ReaderOptions::{core}");
+            carried.push(field.name);
+        }
+        assert_eq!(
+            carried,
+            [
+                "version",
+                "concurrent",
+                "chunk",
+                "gap",
+                "prefetch",
+                "if_match",
+                "if_none_match",
+                "if_modified_since",
+                "if_unmodified_since",
+            ]
+        );
+    }
+
+    /// The `options.py` TypedDicts on main (4ae8e6122 for `ListKwargs`,
+    /// 809b76472 for `StatKwargs`, 501c5d96f for `DeleteKwargs`, f47ec7c1f
+    /// for `ReadKwargs`): the class order and the keys and types of the
+    /// generated classes, with docstrings taken from core.
+    #[test]
+    fn test_options_py_matches_main() {
+        let generated = generated_classes(&core_options(), 
&py_names()).unwrap();
+        let py = render_options_py(&crate::workspace_dir(), 
&generated).unwrap();
+        let classes: Vec<&str> = py
+            .lines()
+            .filter_map(|line| line.strip_prefix("class "))
+            .map(|class| class.split('(').next().unwrap())
+            .collect();
+        assert_eq!(
+            classes,
+            [
+                "ReadKwargs",
+                "WriteKwargs",
+                "ListKwargs",
+                "StatKwargs",
+                "CopyKwargs",
+                "RenameKwargs",
+                "DeleteKwargs",
+                "OpenKwargs",
+            ]
         );
 
         // The `identifier: type` lines of a class body; docstring lines are
@@ -2118,6 +2874,25 @@ print(json.dumps(docs))
                 .map(String::from)
                 .collect()
         };
+        assert_eq!(
+            keys("ReadKwargs", "WriteKwargs"),
+            [
+                "version: str",
+                "concurrent: int",
+                "chunk: int",
+                "gap: int",
+                "offset: int",
+                "prefetch: int",
+                "size: int",
+                "if_match: str",
+                "if_none_match: str",
+                "if_modified_since: datetime",
+                "if_unmodified_since: datetime",
+                "content_type: str",
+                "cache_control: str",
+                "content_disposition: str",
+            ]
+        );
         assert_eq!(
             keys("ListKwargs", "StatKwargs"),
             [
@@ -2149,6 +2924,17 @@ print(json.dumps(docs))
 
         // The docstrings parse back, as Python reads them, to the docs.
         let docs = python_docstrings(&py);
+        // `open` in read mode raises some errors differently from `read`,
+        // which the shared `ReadKwargs` docs describe.
+        let open = docs["OpenKwargs"].replace('\n', " ");
+        for name in [
+            "`opendal.exceptions.Unsupported`",
+            "`OSError`",
+            "With a positive `chunk` and no `size`, `open()` first stats the 
file",
+            "or from `seek()` when seeking from the end needs the file's size",
+        ] {
+            assert!(open.contains(name), "{name}");
+        }
         for class in &generated {
             let kwargs = class.name.replace("Options", "Kwargs");
             assert_eq!(docs[&kwargs], class.doc.join("\n"));
@@ -2216,6 +3002,29 @@ print(json.dumps(docs))
         assert!(!methods.contains_key(&("Operator".to_string(), 
"presign_delete".to_string())));
     }
 
+    /// The `read` and `presign_read` keyword arguments and defaults on main
+    /// (f47ec7c1f), copied from `python/opendal/operator.pyi`.
+    #[test]
+    fn test_read_signatures_match_main() {
+        let methods = operator_kwargs();
+        let read = "version=None concurrent=None chunk=None gap=None 
offset=None \
+                    prefetch=None size=None if_match=None if_none_match=None \
+                    if_modified_since=None if_unmodified_since=None 
content_type=None \
+                    cache_control=None content_disposition=None";
+        let presign = "version=None if_match=None if_none_match=None \
+                       if_modified_since=None if_unmodified_since=None 
content_type=None \
+                       cache_control=None content_disposition=None";
+        for (ty, method, kwargs) in [
+            ("Operator", "read", read),
+            ("AsyncOperator", "read", read),
+            ("AsyncOperator", "presign_read", presign),
+        ] {
+            let key = (ty.to_string(), method.to_string());
+            assert_eq!(methods[&key].join(" "), kwargs, "{ty}.{method}");
+        }
+        assert!(!methods.contains_key(&("Operator".to_string(), 
"presign_read".to_string())));
+    }
+
     /// Each method takes the keyword arguments of its options class, and a
     /// keyword whose Rust field is `bool` defaults to `false` while the
     /// others default to `None`.
@@ -2224,7 +3033,8 @@ print(json.dumps(docs))
         let parsed = core_options();
         let methods = operator_kwargs();
         // `scan` is `list` with `recursive=True`, `presign_stat` cannot
-        // request a checksum, and `presign_delete` takes only a version.
+        // request a checksum, `presign_delete` takes only a version, and
+        // `presign_read` takes no range or read tuning.
         for (ty, method, class, omitted) in [
             ("Operator", "list", "ListOptions", &[][..]),
             ("Operator", "scan", "ListOptions", &["recursive"][..]),
@@ -2246,6 +3056,14 @@ print(json.dumps(docs))
                 "DeleteOptions",
                 &["recursive", "if_match"][..],
             ),
+            ("Operator", "read", "ReadOptions", &[][..]),
+            ("AsyncOperator", "read", "ReadOptions", &[][..]),
+            (
+                "AsyncOperator",
+                "presign_read",
+                "ReadOptions",
+                &["concurrent", "chunk", "gap", "offset", "prefetch", 
"size"][..],
+            ),
         ] {
             let class = generated_class(&parsed, class);
             let mut expected: Vec<String> = class
@@ -2283,10 +3101,10 @@ print(json.dumps(docs))
         .unwrap();
 
         let mut mutated = parsed.clone();
-        for options in mutated
-            .iter_mut()
-            .filter(|o| ["ListOptions", "StatOptions", 
"DeleteOptions"].contains(&o.name.as_str()))
-        {
+        for options in mutated.iter_mut().filter(|o| {
+            ["ListOptions", "StatOptions", "DeleteOptions", "ReadOptions"]
+                .contains(&o.name.as_str())
+        }) {
             for (name, kind) in [
                 ("fake_option", OptionKind::OptionString),
                 ("fake_flag", OptionKind::Bool),
@@ -2313,6 +3131,8 @@ print(json.dumps(docs))
                 "            fake_flag: false,",
                 "            fake_option: None,",
                 "            fake_flag: false,",
+                "            fake_option: None,",
+                "            fake_flag: false,",
             ]
         );
         let kept: Vec<&str> = rs.lines().filter(|l| 
!l.contains("fake_")).collect();
@@ -2325,7 +3145,7 @@ print(json.dumps(docs))
             options.fields.iter().position(|f| f.name == name).unwrap()
         }
         type Mutation = fn(&mut OptionsStruct);
-        let cases: [(&str, Mutation, &str); 18] = [
+        let cases: [(&str, Mutation, &str); 30] = [
             (
                 "ListOptions",
                 |list| {
@@ -2469,6 +3289,112 @@ print(json.dumps(docs))
                 |delete| delete.has_unmirrored_fields = true,
                 "core DeleteOptions has fields the core options parser skips; 
Python cannot set them",
             ),
+            (
+                "ReadOptions",
+                |read| {
+                    read.fields.remove(position(read, "range"));
+                },
+                "core ReadOptions has no field `range` for Python 
ReadOptions.offset",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "range");
+                    read.fields[i].kind = OptionKind::OptionU64;
+                },
+                "core ReadOptions::range has kind OptionU64; \
+                 Python ReadOptions.offset requires BytesRange",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "concurrent");
+                    read.fields[i].kind = OptionKind::OptionUsize;
+                },
+                "core ReadOptions::concurrent has kind OptionUsize; \
+                 Python ReadOptions.concurrent requires Usize",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "gap");
+                    read.fields[i].kind = OptionKind::Usize;
+                },
+                "core ReadOptions::gap has kind Usize; Python ReadOptions.gap 
requires OptionUsize",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    read.fields
+                        .remove(position(read, 
"override_content_disposition"));
+                },
+                "core ReadOptions has no field `override_content_disposition` \
+                 for Python ReadOptions.content_disposition",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "chunk");
+                    read.fields[i].doc.clear();
+                },
+                "core ReadOptions::chunk has no doc comment",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "chunk");
+                    read.fields[i].doc = vec![
+                        "Refer to the [performance 
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)".to_string(),
+                        "for more details.".to_string(),
+                    ];
+                },
+                "core ReadOptions::chunk has no doc comment that applies to 
Python",
+            ),
+            (
+                "ReadOptions",
+                |read| read.has_unmirrored_fields = true,
+                "core ReadOptions has fields the core options parser skips; 
Python cannot set them",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    for line in &mut read.doc {
+                        *line = line.replace("a zero limit or an empty range", 
"an empty range");
+                    }
+                },
+                "core ReadOptions docs no longer contain \
+                 `A read with a zero limit or an empty range validates`; \
+                 update its Python rewrite in dev/src/generate/python.rs",
+            ),
+            (
+                "ReadOptions",
+                |read| {
+                    let i = position(read, "chunk");
+                    for line in &mut read.fields[i].doc {
+                        *line =
+                            line.replace("unless `content_length_hint` is 
set", "unless hinted");
+                    }
+                },
+                "core ReadOptions docs no longer contain \
+                 `, unless `content_length_hint` is set.`; \
+                 update its Python rewrite in dev/src/generate/python.rs",
+            ),
+            (
+                "ReaderOptions",
+                |reader| {
+                    reader.fields.remove(position(reader, "prefetch"));
+                },
+                "core ReaderOptions has no field `prefetch` for Python 
ReadOptions.prefetch",
+            ),
+            (
+                "ReaderOptions",
+                |reader| {
+                    let i = position(reader, "prefetch");
+                    reader.fields[i].kind = OptionKind::OptionUsize;
+                },
+                "core ReaderOptions::prefetch has kind OptionUsize; \
+                 Python ReadOptions.prefetch requires Usize",
+            ),
         ];
 
         let parsed = core_options();
@@ -2485,23 +3411,37 @@ print(json.dumps(docs))
     }
 
     /// A table row must name each keyword and core field once, and use a
-    /// pair of core kind and Rust type that the generator can convert.
+    /// pair of core kind and Rust type that the generator can convert. Only
+    /// `offset` and `size` set a range, together, each with a Python doc. A
+    /// field of another core struct must exist, and every Python doc must
+    /// belong to a listed keyword.
     #[test]
     fn test_options_table_rejects_bad_rows() {
         let parsed = core_options();
         type Rows = &'static [(&'static str, &'static str, OptionKind, 
&'static str)];
-        let cases: [(Rows, &str); 4] = [
+        type Docs = &'static [(&'static str, &'static [&'static str])];
+        const OFFSET: (&str, &str, OptionKind, &str) =
+            ("offset", "range", OptionKind::BytesRange, "Option<u64>");
+        const SIZE: (&str, &str, OptionKind, &str) =
+            ("size", "range", OptionKind::BytesRange, "Option<u64>");
+        const RANGE_DOCS: Docs = &[("offset", &["Offset."]), ("size", 
&["Size."])];
+        let cases: [(&str, Rows, Docs, &str); 10] = [
             (
+                "StatOptions",
                 &[("version", "version", OptionKind::OptionString, "String")],
+                &[],
                 "Python StatOptions.version is a core OptionString with Rust 
type String; \
                  teach dev/src/generate/python.rs about it",
             ),
             (
+                "StatOptions",
                 &[("checksum", "checksum", OptionKind::Bool, 
"Option<String>")],
+                &[],
                 "Python StatOptions.checksum is a core Bool with Rust type 
Option<String>; \
                  teach dev/src/generate/python.rs about it",
             ),
             (
+                "StatOptions",
                 &[
                     (
                         "content_type",
@@ -2516,9 +3456,11 @@ print(json.dumps(docs))
                         "Option<String>",
                     ),
                 ],
+                &[],
                 "Python StatOptions sets core `override_content_type` twice",
             ),
             (
+                "StatOptions",
                 &[
                     (
                         "version",
@@ -2533,13 +3475,80 @@ print(json.dumps(docs))
                         "Option<String>",
                     ),
                 ],
+                &[],
                 "Python StatOptions lists `version` twice",
             ),
+            (
+                "StatOptions",
+                &[(
+                    "version",
+                    "version",
+                    OptionKind::OptionString,
+                    "Option<String>",
+                )],
+                &[("checksum", &["Checksum."])],
+                "Python StatOptions has a doc for `checksum`, which it does 
not list",
+            ),
+            (
+                "ReadOptions",
+                &[
+                    OFFSET,
+                    ("length", "range", OptionKind::BytesRange, "Option<u64>"),
+                ],
+                &[("offset", &["Offset."]), ("length", &["Length."])],
+                "Python ReadOptions.length sets core `range`, a range that 
only \
+                 `offset` and `size` set",
+            ),
+            (
+                "ReadOptions",
+                &[OFFSET],
+                RANGE_DOCS.split_at(1).0,
+                "Python ReadOptions sets core `range` with only one of 
`offset` and `size`",
+            ),
+            (
+                "ReadOptions",
+                &[OFFSET, SIZE],
+                RANGE_DOCS.split_at(1).0,
+                "Python ReadOptions.size needs a Python doc, because core 
documents \
+                 `range` in Rust range syntax",
+            ),
+            (
+                "ReadOptions",
+                &[
+                    OFFSET,
+                    SIZE,
+                    (
+                        "prefetch",
+                        "ReaderOpts::prefetch",
+                        OptionKind::Usize,
+                        "Option<usize>",
+                    ),
+                ],
+                RANGE_DOCS,
+                "core options struct `ReaderOpts` not found for Python 
ReadOptions.prefetch",
+            ),
+            (
+                "ReadOptions",
+                &[
+                    OFFSET,
+                    SIZE,
+                    (
+                        "prefetch",
+                        "ReadOptions::concurrent",
+                        OptionKind::Usize,
+                        "Option<usize>",
+                    ),
+                ],
+                RANGE_DOCS,
+                "Python ReadOptions.prefetch must name core `concurrent` 
without `ReadOptions::`",
+            ),
         ];
-        for (options, error) in cases {
+        for (name, options, docs, error) in cases {
             let spec = PyOptions {
-                name: "StatOptions",
+                name,
                 options,
+                docs,
+                rewrites: &[],
             };
             assert_eq!(
                 py_class(&spec, &parsed, &py_names())
@@ -2548,6 +3557,49 @@ print(json.dumps(docs))
                 error
             );
         }
+
+        // A rewrite applies to docs rendered from core only, so a phrase
+        // that only a Python doc holds still fails generation.
+        let spec = PyOptions {
+            name: "ReadOptions",
+            options: &[OFFSET, SIZE],
+            docs: &[
+                ("offset", &["Offset, in Python words."]),
+                ("size", &["Size."]),
+            ],
+            rewrites: &[("in Python words", "rewritten")],
+        };
+        assert_eq!(
+            py_class(&spec, &parsed, &py_names())
+                .unwrap_err()
+                .to_string(),
+            "core ReadOptions docs no longer contain `in Python words`; \
+             update its Python rewrite in dev/src/generate/python.rs"
+        );
+
+        // `offset` and `size`, in either order, set the range together, and
+        // neither renames a `range` that another doc names.
+        let mut parsed = parsed;
+        let read = parsed.iter_mut().find(|o| o.name == 
"ReadOptions").unwrap();
+        read.doc = vec!["Reads `range`.".to_string()];
+        for options in [&[OFFSET, SIZE][..], &[SIZE, OFFSET][..]] {
+            let spec = PyOptions {
+                name: "ReadOptions",
+                options,
+                docs: RANGE_DOCS,
+                rewrites: &[],
+            };
+            let class = py_class(&spec, &parsed, &py_names()).unwrap();
+            assert_eq!(class.doc, ["Reads `range`."]);
+            let range = class.conversion.iter().find(|f| f.name == 
"range").unwrap();
+            assert_eq!(range.expr, "opts.make_range()");
+            let docs: Vec<String> = class.fields.iter().map(|f| 
f.doc.join("\n")).collect();
+            let expected: Vec<&str> = options
+                .iter()
+                .map(|&(name, ..)| if name == "offset" { "Offset." } else { 
"Size." })
+                .collect();
+            assert_eq!(docs, expected);
+        }
     }
 
     #[test]
@@ -2672,6 +3724,34 @@ print(json.dumps(docs))
         );
     }
 
+    /// Python callers cannot use the Rust performance guide, so a paragraph
+    /// that links it is dropped, and a Rust `Some(value)` reads as the
+    /// Python value.
+    #[test]
+    fn test_py_doc_drops_performance_guide_and_option_wrappers() {
+        let lines = [
+            "Set `chunk`. `Some(0)` has the same behavior as `None`,",
+            "and `Some(\"a\")` reads as `\"a\"`; `Some`, `Some(0`, and 
`IsSome(1)` stay.",
+            "",
+            "Refer to the [performance 
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance)",
+            "for more details.",
+            "",
+            "The 
[specs](https://github.com/apache/opendal/tree/main/core/core/src/docs/specs) 
and",
+            "[performance tips](https://example.com/performance) stay.",
+        ]
+        .map(String::from);
+        assert_eq!(
+            py_doc(&lines, "Test", &py_names(), &[]).unwrap(),
+            [
+                "Set `chunk`. `0` has the same behavior as `None`,",
+                "and `\"a\"` reads as `\"a\"`; `Some`, `Some(0`, and 
`IsSome(1)` stay.",
+                "",
+                "The 
[specs](https://github.com/apache/opendal/tree/main/core/core/src/docs/specs) 
and",
+                "[performance tips](https://example.com/performance) stay.",
+            ]
+        );
+    }
+
     /// Core docs may hold any text: quotes, backslashes, and rewording reach
     /// valid Python with their value intact, and the surface checks, which
     /// pin no core wording, still pass.
@@ -2928,6 +4008,212 @@ print(json.dumps(docs))
         }
     }
 
+    /// Core may reword the `ReadOptions` docs, use either markup for
+    /// capabilities and error kinds, and reword the docs that Python
+    /// replaces: the surface checks, which pin no core wording, still pass,
+    /// the Python docs stay, and Python reads back each docstring.
+    #[test]
+    fn test_read_options_survive_core_rewording() {
+        let mut parsed = core_options();
+        let base = generated_class(&parsed, "ReadOptions");
+        let read = parsed.iter_mut().find(|o| o.name == 
"ReadOptions").unwrap();
+        read.doc = [
+            r#""Read" options, with \d."#,
+            "",
+            "A missing file returns",
+            "`ErrorKind::NotFound`, a failed condition returns 
[`crate::ErrorKind::ConditionNotMatch`],",
+            "and a missing capability returns 
[`ErrorKind::Unsupported`](crate::ErrorKind::Unsupported).",
+            "",
+            r#"A read with a zero limit or an empty range validates "its" 
options,"#,
+            "then returns an empty buffer without accessing storage.",
+            "",
+            "Refer to the [performance 
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance).",
+        ]
+        .map(String::from)
+        .to_vec();
+        for field in &mut read.fields {
+            let mut doc = vec![format!(
+                r#"Reworded "{}" doc, see [the spec][crate::docs::specs::x]."#,
+                field.name
+            )];
+            if let Some(python) = base.fields.iter().find(|f| f.core == 
field.name) {
+                for (i, name) in spans(&python.doc, "op.capability().")
+                    .into_iter()
+                    .enumerate()
+                {
+                    doc.push(match i % 2 {
+                        0 => format!("Check `Capability::{name}`."),
+                        _ => format!("Check 
[`Capability::{name}`](crate::Capability::{name})."),
+                    });
+                }
+                for name in spans(&python.doc, "opendal.exceptions.") {
+                    doc.push("It returns".to_string());
+                    doc.push(format!("[`crate::ErrorKind::{name}`]."));
+                }
+            }
+            if field.name == "chunk" {
+                doc.push("`Some(0)` equals `None`.".into());
+                doc.push(
+                    "A positive `chunk` and an open-ended or nonempty suffix 
range first stat, \
+                     unless `content_length_hint` is set."
+                        .into(),
+                );
+                doc.push(String::new());
+                doc.push("Refer to the [performance 
guide](https://github.com/apache/opendal/tree/main/core/core/src/docs/performance).".into());
+            }
+            if field.name == "override_content_type" {
+                doc.push(
+                    "Pairs with 
[`override_cache_control`](Self::override_cache_control).".into(),
+                );
+            }
+            field.doc = doc;
+        }
+        let reader = parsed
+            .iter_mut()
+            .find(|o| o.name == "ReaderOptions")
+            .unwrap();
+        for field in &mut reader.fields {
+            field.doc = vec![format!("Reworded reader {} doc.", field.name)];
+        }
+
+        let generated = generated_classes(&parsed, &py_names()).unwrap();
+        let class = generated.iter().find(|c| c.name == 
"ReadOptions").unwrap();
+        assert_read_surface(class);
+
+        let py = render_options_py(&crate::workspace_dir(), 
&generated).unwrap();
+        let docs = python_docstrings(&py);
+        assert_eq!(
+            docs["ReadKwargs"],
+            "\"Read\" options, with \\d.\n\
+             \n\
+             A missing file raises\n\
+             `opendal.exceptions.NotFound`, a failed condition raises \
+             `opendal.exceptions.ConditionNotMatch`,\n\
+             and a missing capability raises 
`opendal.exceptions.Unsupported`.\n\
+             \n\
+             A read with `size=0` validates \"its\" options,\n\
+             then returns empty bytes without accessing storage."
+        );
+        assert_eq!(
+            docs["ReadKwargs.chunk"],
+            "Reworded \"chunk\" doc, see the spec.\n\
+             Check `op.capability().stat_with_if_modified_since`.\n\
+             It raises\n\
+             `opendal.exceptions.Unsupported`.\n\
+             `0` equals `None`.\n\
+             A positive `chunk` and no `size` first stat."
+        );
+        assert_eq!(
+            docs["ReadKwargs.content_type"],
+            "Reworded \"override_content_type\" doc, see the spec.\n\
+             Pairs with `cache_control`."
+        );
+        assert_eq!(
+            docs["ReadKwargs.if_match"],
+            "Reworded \"if_match\" doc, see the spec.\n\
+             Check `op.capability().read_with_if_match`.\n\
+             It raises\n\
+             `opendal.exceptions.ConditionNotMatch`.\n\
+             It raises\n\
+             `opendal.exceptions.NotFound`.\n\
+             It raises\n\
+             `opendal.exceptions.Unsupported`."
+        );
+        for (name, doc) in READ_PYTHON_DOCS {
+            assert_eq!(docs[&format!("ReadKwargs.{name}")], doc, "{name}");
+        }
+        for field in &class.fields {
+            assert_eq!(
+                docs[&format!("ReadKwargs.{}", field.name)],
+                field.doc.join("\n")
+            );
+        }
+    }
+
+    /// The hand-written `read` docstrings in `bindings/python/src/operator.rs`
+    /// agree with the generated `ReadOptions` docs: both name the overrides
+    /// that a positive `prefetch` rejects with `ValueError`, which
+    /// `use_prefetch_reader` in `bindings/python/src/options.rs` checks, and
+    /// both say that `gap` has no effect.
+    #[test]
+    fn test_read_docstrings_agree_with_read_options() {
+        let root = crate::workspace_dir().join("bindings/python/src");
+        let operator = fs::read_to_string(root.join("operator.rs")).unwrap();
+        let options = fs::read_to_string(root.join("options.rs")).unwrap();
+        let class = generated_class(&core_options(), "ReadOptions");
+        let doc = |name: &str| {
+            class
+                .fields
+                .iter()
+                .find(|f| f.name == name)
+                .unwrap()
+                .doc
+                .join(" ")
+        };
+
+        let check = options
+            .split_once("pub fn use_prefetch_reader(&self)")
+            .unwrap()
+            .1
+            .split_once("\n    }\n")
+            .unwrap()
+            .0;
+        let rejected: Vec<&str> = class
+            .fields
+            .iter()
+            .filter(|f| check.contains(&format!("self.{}.is_some()", f.name)))
+            .map(|f| f.name)
+            .collect();
+        assert_eq!(
+            rejected,
+            ["content_type", "cache_control", "content_disposition"]
+        );
+
+        let prefetch = doc("prefetch");
+        let notes = "A positive `prefetch` cannot be combined with 
`content_type`,\n    \
+                     /// `cache_control`, or `content_disposition`. Combining 
them raises `ValueError`.";
+        assert_eq!(
+            operator.matches(notes).count(),
+            2,
+            "Operator.read and AsyncOperator.read"
+        );
+        for name in rejected {
+            assert!(prefetch.contains(&format!("`{name}`")), "{prefetch}");
+        }
+        assert!(prefetch.contains("raises `ValueError`"), "{prefetch}");
+
+        assert!(doc("gap").ends_with("so `gap` has no effect."));
+        // Both `read` docstrings describe `prefetch` with the first sentence
+        // of its option doc.
+        let comments: String = operator
+            .lines()
+            .filter_map(|line| line.trim_start().strip_prefix("///"))
+            .map(str::trim)
+            .collect::<Vec<_>>()
+            .join(" ");
+        let summary = prefetch.split_once(". ").unwrap().0;
+        assert_eq!(
+            comments.matches(&format!("{summary}.")).count(),
+            2,
+            "Operator.read and AsyncOperator.read: {summary}"
+        );
+
+        // `open` names the same deferred errors as `OpenKwargs`.
+        let seek = "read methods, or from `seek()` when seeking from the end 
needs the";
+        assert_eq!(
+            operator.matches(seek).count(),
+            2,
+            "Operator.open and AsyncOperator.open"
+        );
+        let gap = "    /// gap : int, optional\n    \
+                   ///     Has no effect, because `read()` reads a single byte 
range.\n";
+        assert_eq!(
+            operator.matches(gap).count(),
+            2,
+            "Operator.read and AsyncOperator.read"
+        );
+    }
+
     /// Every capability and exception the generated docstrings name exists
     /// in the Python API: `python/opendal/capability.pyi` and
     /// `python/opendal/exceptions.pyi`.
@@ -2988,6 +4274,23 @@ print(json.dumps(docs))
                 ][..],
                 &["ConditionNotMatch", "Conflict", "Unsupported"][..],
             ),
+            (
+                "ReadOptions",
+                &[
+                    "read_with_version",
+                    "stat_with_if_modified_since",
+                    "read_with_if_match",
+                    "read_with_if_none_match",
+                    "read_with_if_modified_since",
+                    "read_with_if_unmodified_since",
+                ][..],
+                &[
+                    "ConditionNotMatch",
+                    "NotFound",
+                    "RangeNotSatisfied",
+                    "Unsupported",
+                ][..],
+            ),
         ] {
             let class = generated_class(&parsed, class);
             let docs: Vec<String> = class

Reply via email to