Skip to content

Append to the cache of a dataset without shape without copying it - #8785

Open
Jakob Holz (Jajaho) wants to merge 8 commits into
microsoft:mainfrom
Jajaho:fix/cache-append-without-copy
Open

Jakob Holz (Jajaho) wants to merge 8 commits into
microsoft:mainfrom
Jajaho:fix/cache-append-without-copy

Conversation

@Jajaho

@Jajaho Jakob Holz (Jajaho) commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

For a dataset without a shape, _insert_into_data_dict appended each result to the cache with np.append, which copies all data collected so far. The time of add_result therefore grew with the length of the run, and a run of N results copied O(N²) data. This applies to DataSet and DataSetInMem alike, since both fill the cache.

Measured with two array parameters of 16384 values and one setpoint array per result (a scope recording), median time of add_result:

Result DataSetInMem before DataSet before DataSetInMem after DataSet after
0 4.4 ms 4.4 ms 0.3 ms 0.8 ms
400 70 ms 76 ms 0.3 ms 0.4 ms
750 128 ms 120 ms 0.3 ms 0.4 ms

On a Red Pitaya scope, a recording of 1000 captures went from 7.4 captures/s on average (54 ms per capture at the start, 186 ms after 800) to a constant 19 captures/s, limited by the instrument read.

The cache now stores such arrays as views of the beginning of a larger buffer and appends into its spare rows; a full buffer is replaced by one with 1.5 times the rows required, so the copies amount to a few times the data in total. The arrays returned by cache.data() have the values, dtype and shape np.append gave them.

  • Appends that np.append would promote to another dtype or another shape after the first axis, appends whose cast np.append rejects under same_kind (timedelta64 to datetime64), and arrays of objects still go through np.append. So does an append whose write into the buffer raises ValueError (bytes that are not ASCII appended to an array of str).
  • Only the array _append_rows returned last for a buffer is extended in place: a module-level map from the id of each buffer to a weak reference to that array (removed by weakref.finalize when the buffer is collected) identifies it. Any other array is copied, whatever its base, layout or dtype: arrays passed to add_result, which may themselves be views of a larger array, other views of a buffer (transposed, reinterpreted, strided), and an array that two caches share, once the first of them has appended. An append takes the entry out of the map while it writes, so two threads cannot extend the same array in place.
  • The shaped path is unchanged.
  • The cache takes up to 1.5 times the memory of its data.

Tests:

  • test_cache_append_without_shape_does_not_copy_collected_data (DataSet and DataSetInMem): 100 appends copy the data at most 12 times; it fails without the change (99 copies).
  • test_cache_append_without_shape_promotes_dtype_and_keeps_input_arrays: an integer column followed by floats becomes float64 as with np.append, and an array whose views were passed as values is left unchanged (add_result copies the values, so the check of _append_rows is tested on its own below).
  • test_append_rows_does_not_write_to_arrays_it_did_not_allocate: _append_rows with the first rows of an array it did not allocate, with spare rows behind them, leaves that array unchanged and returns the result of np.append.
  • test_append_rows_extends_only_the_array_it_returned_last (transposed, reinterpreted and strided view of a buffer, each with the buffer's first address and as many rows as are filled): the result equals that of np.append; all three fail with the earlier comparison of layouts.
  • test_append_rows_extends_a_shared_array_only_once: of two appends to the same array, only the first uses the spare rows behind it; the second copies, and the shared array is unchanged.
  • test_append_rows_extends_a_shared_array_in_one_thread_only: of two threads that append to the same array, the first is stopped after it has written its row; the second copies, and each result contains its own row.
  • test_insert_into_data_dict_rejects_timedelta_appended_to_datetime (an array in a buffer and one that is not, two units): raises the TypeError of np.append and leaves the existing array unchanged; a datetime64 appended afterwards is written into the buffer.
  • test_insert_into_data_dict_falls_back_where_the_append_into_a_buffer_fails and test_insert_into_data_dict_appends_ascii_bytes_to_str_into_a_buffer: bytes that are not ASCII appended to an array of str give the array of objects of main; ASCII bytes are written into the buffer.
  • The existing tests in tests/dataset/test_data_set_cache.py, which compare the cache with the database for many layouts, pass.

Without a shape, _insert_into_data_dict appended each result with np.append,
which copies all data collected so far, so the time of add_result grew with
the length of the run. With two arrays of 16384 values per result, add_result
took 4 ms at the start and 128 ms after 750 results, for DataSet and
DataSetInMem alike.

The cache now stores such arrays as views of the beginning of a larger
buffer and appends into its spare rows; a full buffer is replaced by one of
1.5 times the rows required. Appends that np.append would promote to another
dtype or shape, and arrays of objects, still go through np.append. Arrays
passed to add_result are never written to.
@Jajaho
Jakob Holz (Jajaho) requested a review from a team as a code owner November 20, 2026 02:30
@Jajaho

Copy link
Copy Markdown
Contributor Author

Some background on where this came up.

Our lab's bench software is built on QCoDeS. It records oscilloscope traces (a Red Pitaya scope, 2 × 16384 samples per capture) as runs. Each capture is one add_result on a Measurement: the capture number, the time since the first capture, the time axis and both traces as paramtype="array". A recording is either a set number of captures or runs until the operator stops it, which can mean thousands of captures. It is stored either as a DataSetInMem, exported to NetCDF at the end, or crash-safe as a DataSet.

Long recordings got slower and slower: 47 ms per capture at the start, 265 ms after 1300 captures. We traced that to the np.append in _insert_into_data_dict.

We looked at declaring a shape with Measurement.set_shapes(), which avoids the copy, but it doesn't fit this case:

  • A recording that runs until stopped has no number of captures to declare.
  • A DataSetInMem that stops before its shape is filled cannot be exported. export() raises ValueError: Dependency 'x' does not define an axis of length 10: found 4 unique values, so an aborted in-memory recording would lose its data.
  • A shape preallocates, and fills with NaN, the full size of the run at the start.

So unshaped runs are the normal case for this kind of acquisition. Until a release contains this change, we install the same append as a replacement for _insert_into_data_dict in our own code. We would much rather drop that.

A related observation, outside this PR: in the crash-safe DataSet, the cache keeps a second copy of everything already written to the database. With this change it no longer costs time, but it still grows with the run, about 1 GB after 1300 captures of two traces. For these runs we read the data back from the database or the exported NetCDF, and nothing reads the cache. (In a DataSetInMem the cache is the data, of course.) Would an opt-in setting to not keep a cache for a DataSet be welcome as a separate PR?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The fixed 16-row minimum exceeds the stated 1.5× memory bound and can cause allocation failures, while the ownership regression test does not actually exercise caller-buffer protection.

2 open issues
What changed in this PR

This PR reduces repeated copying when appending results to QCoDeS dataset caches without a declared shape, benefiting both DataSet and DataSetInMem.

Changes:

  • Adds reusable, geometrically growing buffers for compatible arrays, retaining np.append fallbacks.
  • Adds regression tests for copy frequency, dtype promotion, and input preservation.
  • Documents the performance improvement in a newsfragment.
File Description
tests/​dataset/​test_data_set_cache.py Adds append-performance and data-integrity regression tests.
src/​qcodes/​dataset/​data_set_cache.py Implements buffer-backed appends and tracks buffer ownership.
docs/​changes/​newsfragments/​8785.improved Announces faster appends for datasets without a declared shape.

Review effort: Balanced

Comment thread src/qcodes/dataset/data_set_cache.py Resolved
Comment thread tests/dataset/test_data_set_cache.py Resolved
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.56%. Comparing base (29fe8a6) to head (5bb2abe).
⚠️ Report is 170 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8785      +/-   ##
==========================================
+ Coverage   77.76%   78.56%   +0.80%     
==========================================
  Files         308      311       +3     
  Lines       32855    33184     +329     
==========================================
+ Hits        25549    26071     +522     
+ Misses       7306     7113     -193     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jenshnielsen

Copy link
Copy Markdown
Collaborator

Thanks Jakob Holz (@Jajaho) Looks like a worthwhile fix. I will need a bit of time looking at it.

Jakob Holz (Jajaho) and others added 2 commits November 24, 2026 04:01
The minimum was a deliberate trade of memory for speed: spare rows at the start of a run in exchange for fewer buffer replacements. We now measured whether the trade pays off, and decided against it. The floor is therefore dropped and a const. x1.5 buffer size is used.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
DataSaver.add_result copies each value with np.array, so the test through
Measurement never passes a view of the caller's array to the cache and
holds with or without the ownership check of _append_rows.

The new test calls _append_rows with the first rows of an array that it
did not allocate, with spare rows behind them, and asserts that the whole
array is unchanged. It fails if the check on _buffer_rows is removed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The append fast path can silently change stored values when reusing incompatible buffer views and raise an uncaught UnicodeDecodeError instead of reaching the object-array fallback.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Catch fast-path assignment errors to allow fallback

src/​qcodes/​dataset/​data_set_cache.py:483

Appending np.array([b'\xff']) after np.array(['a']) passes the fast-path dtype check but raises UnicodeDecodeError during assignment. Because _append_rows is outside the try, this supported array-parameter input now fails instead of reaching the existing object-array fallback. Move the fast-path call inside the same try.

2 resolved since last review

Review effort: Max

Comment thread src/qcodes/dataset/data_set_cache.py Resolved
The check before writing into spare rows compared the base, the number of
filled rows, the shape after the first axis and the first address. A
transposed or dtype-reinterpreted view of a buffer, or one with a step
along the first axis, can match all of these while having another layout;
the append then returned the buffer's rows in the buffer's layout and
silently changed the values stored before. Such a view reaches the cache
through add_data, which stores an array passed to an empty cache as it is.

_append_rows now keeps a weak reference to the array it returned last for
each buffer and extends only that array in place; any other array is
copied, whatever its base, layout or dtype. This replaces the row count
and the comparisons of address and shape. Of an array that two caches
share, only the first to append uses the spare rows.

The test of views fails without the change for all three views.
Bytes that are not ASCII appended to an array of str pass the dtype check
of _append_rows, but raise UnicodeDecodeError when written into the buffer.
Since the call was outside the try, the error reached the caller instead
of the fallback to an array of objects that np.append reaches on main.
A ValueError of _append_rows now leaves the append to np.append.
@Jajaho
Jakob Holz (Jajaho) force-pushed the fix/cache-append-without-copy branch from 93b1b5b to 3ad0017 Compare November 30, 2026 10:34
@Jajaho

Copy link
Copy Markdown
Contributor Author

On the issue in Copilot's second review that has no inline thread (Catch fast-path assignment errors to allow fallback, data_set_cache.py:483):

Confirmed with NumPy 2.5.5: appending np.array([b"\xff"]) to np.array(["a"]) raised UnicodeDecodeError. np.result_type("<U1", "S1") is <U1, so the dtype check of _append_rows accepts the bytes, and decoding them fails only when they are written into the buffer. On main the same error comes from np.append, and since UnicodeDecodeError is a ValueError, it reaches the fallback to an array of objects.

3ad0017 catches a ValueError of _append_rows and leaves the append to np.append, instead of moving the call into the existing try as suggested. The result is then always that of np.append, its fallback included; with the call inside the try, any ValueError of _append_rows would go straight to the array of objects, even one that np.append would not raise. The values already collected are unchanged by the failed write, which reaches only the spare rows of the buffer.

test_insert_into_data_dict_falls_back_where_the_append_into_a_buffer_fails covers a new buffer and the in-place append into a buffer's spare rows; both raised UnicodeDecodeError before the change. test_insert_into_data_dict_appends_ascii_bytes_to_str_into_a_buffer checks that ASCII bytes still use the buffer, with the result of np.append.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Buffer reuse can silently corrupt cached data because it permits unsafe dtype casts, trusts mutable array metadata, and does not atomically claim shared buffer tails.

No open issues 🎉

3 previously missed issues

In code that hasn't changed since last review

High severity Check same-kind cast safety before reusing the array

src/​qcodes/​dataset/​data_set_cache.py:451

Dtype promotion alone does not make assignment equivalent to np.append. Combining datetime64[D] with timedelta64[D] produces the existing datetime dtype, but np.append(..., axis=0) rejects that cast under same_kind. The assignment below permits an unsafe cast instead, silently storing a one-day duration as 1970-01-02; both input dtypes are allowed for array parameters. Also require np.can_cast(new_values.dtype, existing_values.dtype, casting="same_kind") before taking the fast path. NumPy's cast resolver on its default branch at 9697df5 marks this conversion unsafe.

High severity Claim buffer tails atomically to prevent concurrent overwrites

src/​qcodes/​dataset/​data_set_cache.py:457

If two caches share a tracked array and append from different threads, both can pass this check before either updates _buffer_tails. They then overwrite the same spare rows, so one cache can retain the other cache's values. Atomically claim the tail before writing so the competing append allocates its own buffer.

Medium severity Validate tracked array metadata before reusing its buffer

src/​qcodes/​dataset/​data_set_cache.py:461

The tracked array is returned directly by cache.data(), so its dtype or strides can be changed in place without changing its identity. For example, after two float array results, setting the returned array's dtype to np.int64 and appending an integer result passes this check, but writes into the float buffer and returns a float array instead of the integer result np.append would produce. Check that the tracked array still has the buffer's dtype, trailing shape and strides before reusing it; otherwise copy it.

1 resolved since last review

Review effort: Max

np.result_type gives the dtype of the existing array for timedelta64
appended to datetime64, so _append_rows wrote the new values into the
buffer. An assignment casts with the rule "unsafe" and stored the duration
as a date counted from 1970-01-01, where np.append casts with "same_kind"
and raises TypeError, as on main.

_append_rows now also returns None if the new values cannot be cast to the
dtype of the existing array with "same_kind". Of 20 dtypes appended to
each other, this pair was the only one with a result other than that of
np.append; no other pair leaves the buffer.
_append_rows read the entry of a buffer with get and set it again after
writing. Two threads that append to the same array, as two caches holding
it can, both passed the check before either had recorded the array it
returns; both wrote into the same spare rows, and one result contained the
row of the other thread.

The entry is now taken out of the dict with pop and set again after the
write. Only one thread receives it and writes into the spare rows; the
other finds no entry and copies. An append that does not extend the array
in place sets the entry it removed again, so the result of appends from
one thread is unchanged.

The test stops the first thread after it has written its row and before it
sets the entry, runs the second, and fails without the change.
@Jajaho

Copy link
Copy Markdown
Contributor Author

On the three findings of the review of 1 December:

Same-kind cast (line 451). Confirmed. Through Measurement with paramtype="array", a datetime64[D] result followed by a timedelta64[D] result raises TypeError on main and was stored as 1970-01-02 with this PR, for both dataset classes. fb1468f adds the condition you propose: _append_rows returns None if the new values cannot be cast to the dtype of the existing array with same_kind, so the append is left to np.append and raises as on main.

We compared the result with that of main for 20 dtypes appended to each other (bool, integers, floats, complex, str, bytes, datetime64 and timedelta64 in three units), each for an array in a buffer and for one that is not: 12 of 800 cases differed, all of them timedelta64 appended to datetime64. With the condition none differ, and no other pair leaves the buffer. 1000 appends of a scalar take 1.8 ms instead of 1.5 ms; for arrays of 16384 values the time is unchanged.

test_insert_into_data_dict_rejects_timedelta_appended_to_datetime covers it and fails without the change.

Concurrent appends to a shared array (line 457). Confirmed for _append_rows called from two threads with the same array: one result contained the row of the other thread in 300 of 300 trials for rows of 100 000 values. It requires two caches that hold the same array object. DataSaver.add_result copies every value, so this only occurs if the array returned by cache.data() of one dataset is passed to add_data of another dataset's empty cache. Since the PR states that only the first cache to append writes into the buffer in that case, it should hold across threads as well.

5bb2abe takes the entry of the buffer out of _buffer_tails with pop instead of reading it with get, and sets it again after the write. Only one thread receives the entry; the other finds none and copies. An append that does not extend the array in place sets the entry it removed again, so appends from one thread behave as before. No lock is needed, and the time per append is unchanged.

test_append_rows_extends_a_shared_array_in_one_thread_only stops the first thread after it has written its row and before it sets the entry, then runs the second. It fails without the change.

Metadata of the returned array changed in place (line 461). Not changed. Assigning to dtype of the array returned by cache.data() changes the array the cache stores, on main as well: before any append, the cache then contains the float values reinterpreted as integers (4607182418800017408 for 1.0). The append is not what alters the data in this case. NumPy 2.5 deprecates setting dtype and shape on an array. If the check is wanted regardless, it is a comparison of dtype, strides and shape after the first axis against the buffer.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants