Skip to content

[Bug]: Undo steps on a large layer each hold a full copy of its rows, so memory grows with every edit #2431

Open

Description

@Mavrick-F

Before you start

  • I searched the existing issues and did not find a duplicate.
  • This is a bug report, not a usage question.

What happened?

On a large layer, each edit leaves a full copy of the layer's rows in the Undo history, so memory use rises with every edit. Enough edits reach the machine's limit, and running out of memory ends the process, so unsaved edits are lost.

With a generated table of 300,000 rows and 62 fields (script below), each edit.setValue added about 0.74 GB:

Edits Peak memory
0 1.9 GB
4 3.7 GB
8 6.7 GB
12 9.7 GB

A county parcel layer (448,126 features, 121 fields) follows the same pattern at about 1.8 GB and 1.2 s per edit. Field edits do too: in the join-and-calculate workflow on #1998's size line, Add Field and Calculate Field together account for 4.5 GB of a 9.4 GB peak.

Cause

A layer's rows are one shared block (Features { rows: Arc<Vec<Feature>> } in crates/data/src/lib.rs), which keeps project snapshots cheap. Each editing command takes a snapshot in Session::guarded_inner (crates/engine/src/lib.rs). The session restores it if the command fails, and otherwise keeps it as the Undo step. The command's first write goes through Arc::make_mut, which finds the block shared with the snapshot and copies all of its rows. So each edit copies the layer once, however small the change, and each Undo step keeps its own version of the layer, up to UNDO_LIMIT (40) steps.

Most of the copy is attribute values rather than geometry. The parcels have 54 million attribute values and 5.2 million vertices, so sharing geometry between versions would not help much on its own.

Steps to reproduce

python3 - <<'EOF'
import csv, random
random.seed(1)
with open("rows.csv", "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["x", "y"] + [f"f{i}" for i in range(60)])
    for _ in range(300_000):
        w.writerow([round(random.uniform(-93.5, -93.1), 6), round(random.uniform(44.8, 45.2), 6)]
                   + [random.randint(0, 10**6) if i % 2 else f"text {random.randint(0, 999)}" for i in range(60)])
EOF

edits() { for ((i=0; i<$1; i++)); do printf -- '--cmd\0edit.setValue={"layer":"rows","row":%d,"field":"f1","value":%d}\0' $i $i; done; }
for n in 0 4 8 12; do
  edits $n | xargs -0 /usr/bin/time -f "$n edits: %M KB peak" \
    rustgis-cli run --cmd 'layer.addData={"path":"rows.csv","name":"rows"}' >/dev/null
done

The first edit fits within the peak that reading the CSV leaves behind, so the growth shows from the second edit on.

Expected behavior

  • An edit's memory cost is in proportion to what it changes.
  • Memory use doesn't keep rising with the number of edits.
  • When an operation won't fit in memory, RustGIS refuses it with a message, or says what it gave up, such as older Undo steps.

Possible fixes

These are independent and can land in any order.

  1. Bound Undo by memory as well as by step count. When the steps that hold their own copies pass a budget, the session drops the oldest and says how many it dropped. This stops the growth, though each edit still makes one copy while it runs. It stays in the engine and changes no saved file or command parameter.
  2. Add a memory regression test to CI. A fixed CLI workflow on generated data (load, Add Field, Calculate Field, Join Field, export, several edits) would check peak memory as a multiple of the loaded size. The limits start at today's values and come down as fixes land, so a new full copy from any source fails the test. It would run on Linux and needs no new dependency.
  3. Count the memory the session already holds. Each limit today plans for its own share of memory (memory::SHARE) without counting the layers, Undo steps and tool outputs already held. That is problem 3 in Analysis limits: fail gracefully on allocation, scale with the machine, and cancel long runs #1291, which the work there solved for rasters. With an estimate of what is held, an operation that copies a layer could check that the copy fits before making it. This would build on Analysis limits: fail gracefully on allocation, scale with the machine, and cancel long runs #1291 and feat(data): the size of a file read into memory follows the computer's memory #2411.
  4. Store rows so that unchanged values are shared, in shared blocks or with attribute values by column. An edit would then copy only the block or column it changes, Add Field would add a single column, and Join Field could share its target's columns. This changes Feature/Features, which is the lead's decision, and it relates to the Exploratory item on per-feature memory in Tracking: large data (layers over 2 million features, slow hillshade and GeoTIFF writing) #1111, so it needs its own proposal. The saved project format can stay as it is.

I can take 1 and 2. 3 overlaps the memory-limit work, so we should agree who takes it first.

@opengeos/rustgis-maintainers, for 3 and 4. Related: #1111 (large data), #1291 and #2411 (memory limits), #1998 (where this was found).

How are you running RustGIS?

Command line (rustgis-cli)

Version

62526f0

Operating system, browser and graphics

Debian 13, 31 GB of memory

Sample data

The generated table above.

Activity

  1. added
    bug
    on Nov 19, 2026
  2. pick2510 commented on Nov 19, 2026

    @pick2510
    Contributor

    @Mavrick-F I'll take 3. It continues the memory-limit work in #1291 and #2411 (merged), where the limits already follow the computer's memory through memory::physical(), and #2441's check will show whether it helps. 1 is in with #2437, and 2 is #2441.

    I'll post the plan here before starting, covering three things:

    • how the session estimates what it holds (layers, Undo steps, tool outputs);
    • which operations check that a copy fits before making it;
    • what they say when it doesn't.

    4 stays with the lead's proposal.

  3. pick2510 commented on Nov 19, 2026

    @pick2510
    Contributor

    For the longer term, an option beside 4, for the lead to weigh: keep a layer's loaded rows unchanged and record edits beside them.

    A base and its edits. A layer would be a read-only base (the rows as loaded) plus a small set of edits keyed by feature id: rows changed, added and deleted. Edits never write to the base. A project snapshot shares the base and copies only the edits, so an Undo step costs what it changed. On the 300,000 × 62 table above, edit.setValue would add one row's values (a few KB) instead of 0.74 GB.

    What else it gives:

    Cost: every reader of Features (drawing, queries, analysis, export, the attribute table) would have to see the base and the edits merged, and do so quickly. That touches far more code than 4, so it would need its own proposal and a PR series measured with #2441's cargo xtask memory. To keep the merged view fast, the edits could be folded into a new base once they grow past a share of it, or when a project is saved.

    Limits: an edit that touches every row (Add Field, Calculate Field over the whole layer) produces edits as large as the base. Storing attributes by column (4) is what fixes those, so the two would complement each other.

    This doesn't change 3. The estimate of what the session holds works the same way, and with a shared base its numbers get smaller.

  4. pick2510 commented on Nov 19, 2026

    @pick2510
    Contributor

    Plan for 3, before I start.

    What the session holds. Session keeps an estimate of what it holds: every distinct row allocation in the open project and in Undo and Redo, counted once however many snapshots share it. It reuses #2437's per-allocation estimate and its cache, so the count stays cheap. It adds in-memory rasters and standalone tables, and tool outputs count as the layers they become. The estimate is updated after each command, where #2437 trims the history, and is published to rustgis_data::memory as a process-wide figure. Several sessions in one process, as in Python, add their counts together.

    Room for a copy. A new memory::room() gives the physical memory, minus what is held, minus a reserve for drawing and the window (the quarter that SHARE plans for today). In the browser, or when the memory can't be read, room() is unknown and nothing changes.

    What checks before copying:

    1. Edits of a layer's features or fields (edit.* that change features, including Add Field, Calculate Field and Delete Field). The check runs where streamed layers are refused today, before the command runs. The first write copies the layer's rows because the Undo snapshot shares them, so the copy costs the layer's estimated size. If that doesn't fit in room():
      • Older Undo and Redo steps are dropped until it fits, and the session says how many, as fix(engine): bound undo history by memory #2437 does.
      • If it still doesn't fit with the history empty, the command is refused before anything changes, for example: "Not enough memory to edit Parcels: the edit copies its 1.8 GB of rows, and 22 GB of 31 GB is in use. Remove layers you no longer need or save and reopen the project."
    2. The limits that plan for a share of memory (memory::scaled and the file and project size limits from feat(data): the size of a file read into memory follows the computer's memory #2411). They plan for the smaller of today's share and what room() leaves, so a second large job doesn't plan as if memory were empty. Each limit keeps its floor, so nothing is refused that is accepted today on a machine with free memory. Their errors already name the limit and its value, and they would add what is held when that is the reason.

    Not in this: tools that write a new layer get no check before they run, because their output size isn't known ahead. They are covered by 2 and by the fallible allocations of #1291 step 1. This is engine and data only: no saved file, command parameter or interface change, except the new refusal message, which is translatable.

    Tests: fixed memory amounts are passed in, as scaled takes them today:

    • an edit that fits drops nothing and gives no notice;
    • one that fits after dropping steps gives the notice;
    • one that can't fit is refused with the project and history unchanged.

    I'll measure with #2441's cargo xtask memory once it lands: the edit series in this issue should stop at the machine's limit with the message, instead of being killed.

  5. Mavrick-F commented on Nov 19, 2026

    @Mavrick-F
    MemberAuthor

    More on fix 4, changing how layers are stored. Fixes 1 and 2 are merged (#2437, #2441), and 3 is in #2445.

    On an 8 GB laptop, RustGIS can open and map a county's parcels (450,000 features), but adding one field or making two edits needs more memory than the laptop has free. A layer's attribute values sit in one block, and any change copies the whole block so Undo can keep the old one.

    I tried five ways of storing a layer on those parcels, and one fits: each field's values in their own column, split into chunks that Undo can share. The join-and-calculate job from #1998 dropped from 7.1 GB to 2.1 GB, and to 0.6 GB once the columns are typed. A one-value edit goes from about 1.8 GB to almost nothing. Undo keeps working as it does now.

    Speed holds up. Drawing, labels and tools that read a few fields per feature run as fast as today, and two to three times faster with typed columns. Reading every field of every row, as export and plugins do, gets slower: about half a second more across the whole county.

    This works with pick2510's base-and-edits idea above rather than against it. With shared chunks, a one-value edit already copies only its chunk, about 100 KB, so for edits in memory a separate edit layer adds little. Where base-and-edits matters is a base that stays in the file instead of memory, which is what data bigger than a county needs. Chunks make that easier: edited chunks in memory over chunks read from the file, with Undo working the same way. So I'd do columns first and build that on top.

    The cost is churn. About 900 places in the code read features directly. The plan moves them a crate at a time onto a small set of accessors before storage changes at all, and the storage switch would come back here for a decision first.

    Two things I'd do unless someone sees a problem:

    • Cells that hold a different type than their field, like a number in a text field, stay as they are. Changing storage shouldn't change anyone's data. The readers and commands that produce them get fixed separately, each with its own notice.
    • The first step starts now. It only adds the accessors and a CI check that stops new direct uses from appearing, so it doesn't touch anyone's open work.

    Moving the 900 places would touch the same lines as the coordinate-system work in #2032, so I'll hold that part until #2032 is finished. If it would help to start sooner on files #2032 doesn't touch, say so.

    Measurements

    On the county parcel layer (448,126 features, 121 fields) the rows take 1.47 GB. The cell array is 1.24 GB of that: 54.2 million attribute values at 24 bytes each (size_of::<Value>()). Text is 106 MB and coordinates 84 MB. A smaller Value isn't possible: 24 bytes is already the size of an enum holding a String.

    The layouts were built in a throwaway crate on rustgis-data and run through the join-and-calculate workflow from #1998's size line, keeping a snapshot before every step as Undo does. Peak live heap:

    Layout Peak
    Today, Arc<Vec<Feature>> 7.08 GB
    Rows in shared blocks of 4,096 7.07 GB
    Smaller cells (text interned, flat polygon coordinates) 6.56 GB
    Attribute columns in shared chunks, holding Value 2.11 GB
    Typed attribute columns in shared chunks (geometry also flat, ~50 MB of the saving) 0.57 GB
    • The first row's process peak (9.47 GB) matches rustgis-cli on the same workflow (9.4 GB). The desktop app adds about 0.44 GB.
    • All layouts gave identical results (scan checksums, join and filter counts).
    • Row blocks only fix single-cell edits: Add Field, Calculate Field and Join Field touch every row, so every block.
    • Column sharing gives 3.3×. Join Field keeps every target row in order with the target's fields first, so its output can share all target columns; Add Field adds one column; Calculate Field replaces one. Typing gives another 3.8×.
    • One-cell edit with its Undo snapshot held: +1,470 MB today, +0.1 MB with typed columns.

    Read speed, all 448k parcels, median of 5 (identical checksums):

    Read pattern Today Value columns Typed columns
    Geometry only (drawing) 61 ms 66 ms 22 ms
    5 fields + area (labels, most tools) 102 ms 99 ms 49 ms
    All 121 fields + area (export, plugins, Python) 0.59 s 1.05 s 0.86 s
    1M random single cells 88 ms 107 ms 149 ms
    What it takes besides the storage
    • Column-shaped commands. Calculate Field writes through get_mut and records the old row in design::Change, borrowing rows the command holds; design::apply_with takes 12 ms on 448k changes today because nothing is copied there. Columns have no &Feature to borrow, so change records need a column form, or a port rebuilds the layer as rows (~1.5 GB). Same for Add/Delete Field, Join Field and Delete.
    • Layer identity. About 36 production sites detect "rows changed" through Features::shares, allocation_key or == (edited_streamed, fresh_source_ids, label-state cleanup, time-slider rebind). Replace with an outer Arc that every write replaces, plus a geometry identity so attribute edits don't rebuild projected geometry.
    • Chunked readers. The parcel read peaks 2.8 GB above start because readers build a full Vec<Feature> first.
    • Dense row positions. Selection, label state and parallel caches key on row index; no deletion bitmaps.
    • Off-type cells. No invariant enforces cell type = field type: GeoPackage TEXT holding 42 reads as Int (gpkg.rs), parse_source keeps Float in Integer fields, Dataset::ensure_field ignores an existing field's type. A per-chunk Value fallback keeps today's behaviour; the sources get fixed separately.
    Stages

    Each lands and reverts on its own.

    1. Accessor API on Features (row view, value(row, field), column operations), no behaviour change; plus an xtask count of direct .features/.attrs uses that CI won't let rise (upstream adds ~1,000 such lines a week).
    2. Migrate callers crate by crate (~900 production uses; tests through a to_rows() helper).
    3. Column forms of Calculate Field, Add/Delete Field, Join Field, Delete, on today's storage.
    4. Swap to chunked Value columns with layer and geometry identity. Gate: the workflow ≤ 4.5 GB in the app (what an 8 GB laptop leaves after the OS and a browser); drawing, labels, a per-feature tool, the attribute table and an expression over every row within 1.2× of today, measured back to back; export timed end to end and reported (whole-row reads are 1.5–1.8× slower in the bench).
    5. Readers that emit chunks; projected geometry caches keyed by geometry identity.
    6. Typed columns with per-chunk Value fallback. Decide on arrow-rs here (in Cargo.lock via parquet, dev-only today; measure wasm size first).

    Unchanged throughout: Feature as the public row type (rows can always be built), saved projects, schema/project.schema.json and fixtures, geometry storage (until a separate decision), the plugin interface.

    Later, the same chunks make version comparison cheap (shared chunks compare by pointer) and allow editing layers read in place (edited chunks over file chunks, same snapshot Undo).

  6. pick2510 commented on Nov 19, 2026

    @pick2510
    Contributor

    Plan for 3, part 2: the limits that follow the computer's memory subtract what is already held. It builds on #2445 (part 1), so I'll open it once that is merged.

    What is held, for the whole process. rustgis_data::memory gets a process-wide figure of the memory held:

    What a limit plans for. Today a limit plans for a quarter of the memory (SHARE). It will plan for the smaller of that quarter and what is left of the three quarters after what is held, the same three quarters #2445 checks edits against. On a 16 GB computer holding 4 GB, a job still plans for 4 GB, the same as today. Holding 10 GB, it plans for 2 GB. Every limit keeps its floor and ceiling, so nothing the fixed limits accept today is refused.

    Which limits:

    Left as they are:

    • The project file limit: saving must never be refused because the project is large, and opening one is reading what will become held.
    • Thread scratch: a lower figure would only start fewer threads, at a cost in speed, not in memory held.
    • The Undo budget from fix(engine): bound undo history by memory #2437: it is part of what is held.

    What is said:

    • The refusal of a file that's too large says what is held when holding lowered the limit, for example on a 16 GB computer holding 10 GB: "the most read into memory is 256 MiB on this computer while RustGIS holds 10 GiB of its memory (512 MiB with nothing held): remove layers or tables you no longer need".
    • gp.env returns heldBytes, and its limits are the ones in force at the time.
    • The other limits' errors already give the value they were refused at, which is the lowered one.

    Tests:

    • Fixed memory and held amounts are passed in, as scaled takes them today. Nothing held gives today's limits. Holding up to half the memory changes nothing. Holding more lowers the limits down to their floors, never below.
    • The process-wide figure: two sessions add up, and dropping a session takes its share back. A reservation counts until it is dropped.
    • The file refusal says what is held only when that is the reason.
    • An end-to-end run with test(xtask): peak memory check for command line workflows #2441's RUSTGIS_MEMORY_BYTES: a file read that passes with the project empty is refused once the session holds most of the memory, with the message.

    Engine and data only: no saved file, command parameter or interface change, apart from the message and gp.env's new key.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions