Undo and Redo
This page is the Design Document for the Undo/Redo subsystem and the local transaction log it is built on. To be referred by AI for coding as well as humans. It is a plan; sections marked as locked are decisions, sections marked OPEN are still under debate and must not be treated as settled by an implementer.
The central claim of this document: undo is not a feature, it is a read of the transaction log
in reverse. The same log, read forward, is the collaboration outbox described in
storage.md §10. Building two separate mechanisms would mean two conflict
models, two sequence numbers, and two sources of truth about what changed. So we build the log
once and give it two readers. One honest refinement to that claim: the outbox reader consumes the
log forward plus the inverse transactions that undo/redo synthesise (§5, §8) — an undo moves
the local cursor, but to a peer it is simply the next forward change. The log is still built
once; the two readers just have slightly different views of it.
0. Scope of this iteration
In scope: a per-tab, RAM-only transaction log; undo/redo of property edits, 3D placement moves, in-place 2D transforms, object creation, object deletion, and bulk imports; the ribbon buttons and Ctrl+Z / Ctrl+Y / Delete routing.
Out of scope, deliberately: persisting the log to the .yyy file (the object_undo_log table
specified in storage.md §14.10 is not implemented by this work), and the network layer
itself. The undo history is born when a tab opens and dies when it closes. Saving a file does
not clear it. The log’s format and retention rules are nevertheless written so that the future
network layer can attach to it without reshaping it — that is the point of building one log with
two readers (§7, §8).
1. What the code looks like today
These facts about the existing code drive every decision below. Re-verified against the source after the 10M GPU plan and Step 3A/3B 2D Arena unification (2026-11-28).
1.1 Both worlds now share one unified arena model. 3D geometry (ArenaPageType::World3D),
logical containers (ArenaPageType::Logical), and all nine 2D Cad2D*RecordCPU types
(ArenaPageType::World2D, with variable-length polyline points and UTF-8 text in
ArenaPageType::DynamicBlob) all derive from META_DATA, live in the राम CPU RAM arena under
the tab’s memoryGroupNo, and are indexed in tab.storageObjects3D, tab.storageLogicalObjects,
and tab.storageObjects2D — all kept strictly sorted by memoryID for O(log N) lookup via
ResolveObject / FindGeometryObject3D / FindGeometryObject2D.
The engineering thread is the sole writer of CPU truth in both worlds. The earlier
cpuRecordsMutex and copy-thread 2D CPU record ingestion path no longer exist:
CommandToCopyThread2D now carries only GPU-baked parametric records (UpsertLine,
UpsertMultiLine, UpsertCurve, AppendText, RebuildContainerText, HideObject,
SetSelection). Consequently, there is no 2D CPU ingestion race — undo/redo mutates the
arena object directly on the engineering thread and ships the matching GPU command, identical in
structure to 3D.
1.2 There is no delete operation anywhere in the application. No Commands::EDIT_DELETE, no
ACTION_TYPE for it, and nothing in the codebase pushes CommandToCopyThreadType::REMOVE —
the 3D copy-thread handler at RenderScene3D-DirectX12.cpp:1566 is complete (including
tabRes.registry cleanup and fence-gated retirement of gpuInstanceIndex and instanceSlot)
but currently unreachable. On the 2D GPU side, CommandToCopyThread2DType::HideObject
(RenderPage2D-DirectX12.cpp:913) and RebuildContainerText (RenderPage2D-DirectX12.cpp:900)
already exist and handle hiding deleted lines/curves and re-laying out text. Neither GPU copy
pipeline needs new command types to support Delete/Restore. Since undo of a create is a
delete, the delete primitive is on the critical path (§6).
1.3 Protobuf Encode/Decode is already half-lifted. Every 3D geometry struct already exposes
public encode() and decode() member functions beside its geometry code
(डेटा-सामान्य-3D.cpp, डेटा-पाइप.cpp, डेटा-संरचना.cpp) — including 3D placement. The
remaining 3 logical codecs (EncodeFolder/Page2D/Scene3D) and 9 2D codecs
(EncodeLine2D..DecodeAsset2DInsert) still live in the anonymous namespace of
DataStorage.cpp:59 (lines 247–609). Phase 0 lifts those out and exposes a single uniform
EncodeObjectPayload / DecodeObjectPayload dispatcher across all object types.
One important boundary in those codecs: memoryIDContainer and memoryIDGenerator are NOT
stored inside the protobuf payload (in .yyy, they live in object_store columns rather than
the blob). Because Cad2DCreateAssetFromSelection mutates memoryIDGenerator when re-parenting
selected shapes onto an Asset2DInsert, OBJECT_CHANGE_RECORD must capture
generatorIdBefore / generatorIdAfter explicitly (§3).
1.4 The arena never frees individual objects, and isDeleted is a unified soft flag on
META_DATA (डेटा.h:249). Both 3D and 2D objects inherit META_DATA::isDeleted and
META_DATA::dataVersion (डेटा.h:248). Because राम reclaims memory at tab close via
notifyTabClosed (MemoryManagerCPU.h:358) rather than per-object free:
Undo of a create, and redo of a delete, need no stored payload at all — only a list of object ids and an
isDeletedflag flip. Only update transactions carry before/after bytes.
That single observation is what makes a 50,000-object DXF import cheap to undo. The same fact still has two edges:
- Undo payloads live on the CRT heap, owned by their ring slot (§2.5), not in
राम, so eviction actually reclaims the 256 MB payload budget over a long session. - Decoding an updated
Polyline2DorText2DcallssetPoints()/setText(), which allocates a freshDynamicBlobinराम(ArenaPageType::DynamicBlob). The old blob stays dead in the page until futureDynamicBlobcompaction or tab close — the same accepted cost as soft-deleted objects (§6.4).
1.5 Bulk imports are synchronous on the engineering thread. VishwakarmaExtension.exe runs
out-of-process, but RunQueuedStdImport / RunQueuedDxfImport block until the parsed model is
returned, and ImportStdFileIntoTab (विश्वकर्मा.cpp:1890) / ImportDxfFileIntoTab
(विश्वकर्मा.cpp:1990) materialise every object in one loop on the engineering thread. An import
is therefore an ordinary transaction — begin before the loop, commit after (§6.5). A worker crash
returns null before anything is materialised, so no transaction is left open.
1.6 Keyboard shortcuts are mapped on the engineering thread, not in WndProc. WndProc pushes
raw KEYDOWN into the per-tab userInputQueue and already suppresses that push while a UI text
field has focus (uiKeyboardCaptureCount != 0, Main.cpp:1370, 1410). The engineering
thread’s KEYDOWN switch (विश्वकर्मा.cpp:2678) does the mapping, with modifier state already
tracked in tab.isCtrlDown etc. Ctrl+Z, Ctrl+Y, and Delete follow this exact route and inherit
text-field suppression for free.
1.7 Ribbon runtime state already has an established hook pattern. AllUIControls[] is
constexpr (UserInterface.h:559) and ctrl.isEnabled is static, so there is no runtime
greying hook yet — however, SnapControlLatched(*ribbonTab, ctrl.action)
(UserInterface.cpp:1537) already demonstrates the exact pattern. Phase 2 adds a sibling
ControlRuntimeEnabled(*ribbonTab, ctrl.action) helper consulted by the hover, click, icon, and
text paths (UserInterface.cpp:1540–1610).
2. Locked design decisions
- One chokepoint. Every user mutation to engineering data passes through
TransactionBegin/RecordObjectChange/TransactionCommiton the engineering thread. No mutation site writes an object field without an open transaction. Undo reads the log backwards; the collaboration outbox reads it forwards. The sole sanctioned exclusions areCad2DAutoGenerateDemoContent,Cad2DGenerateBulkLines,Cad2DModifyBulkLines, and the debug/stress hotkeys (विश्वकर्मा.cpp#ifdef _DEBUGblock), which bypass the log so dev scaffolding never floods the undo ring. - Optimistic local-first commit. Every user action mutates local RAM state immediately and
unconditionally in every writable mode — solo, offline, or connected. Committing to the
upstream authority is asynchronous: the network layer (future) reads committed transactions
from the log and submits them; the user is never blocked waiting for the authority. Only when
the authority rejects a transaction is the user interrupted: they are notified and the
rejected work is rolled back on screen (§8). Disconnected editing is not a special mode; it is
just an outbox that has not drained yet (
storage.md§5’s 24-hour grace period bounds it). - Version-guarded undo. Each change record stores
guardVersion(§3, §5). An undo that would overwrite a version it does not recognise is refused, and the user is told why. Undo never silently discards another author’s work. This reuses thecurrent_object_version == base_object_versionrule fromstorage.md§10.3 rather than inventing a second conflict model. - Protobuf payloads. Before/after state is captured as protobuf bytes using the existing
object codecs (§1.3). One byte format for the undo log, the
.yyyfile, and future network transport. Schema-versioned for free. - RAM only, per tab, heap-owned payloads. The log lives in a fixed-slot ring on
DATASETTAB. Payload bytes and change arrays are plain heap allocations owned by their ring slot — notरामarena allocations, becauseरामcannot free individual records (§1.4). They are freed at eviction, redo-stack discard, rejection rollback, and tab close. Engineering objects themselves stay in the arena. Nothing is written to disk. - One user gesture, one transaction. A ribbon click, a committed property edit, a 3D placement move, a completed modal 2D transform, or a delete is exactly one undo step, however many objects it touched. A bulk import is likewise one transaction, undone as a single lot. Export is not a transaction: it mutates nothing.
- View state is not undoable. Camera position, Page2D pan/zoom, selection, sub-tab open/close, pane toggles, snap settings, and per-viewport hide/show visibility masks are not engineering data and never enter the log.
- Redo is cleared by new local gestures only. Committing a new user-initiated transaction
while
undoCursor > 0discards the redo stack. Two things explicitly do not clear it: the inverse transaction an undo publishes to the outbox when connected (§5), and incoming remote deltas (rule 9). No undo trees, no branching history. - Remote deltas never enter the undo ring. Changes published by the authority on behalf of
other authors are applied to local state (via
todoCPUQueueon the engineering thread) but are not undoable here. Ctrl+Z operates on my gestures only; another author’s change can only be reversed by editing it, which creates a new transaction of mine (§8).
3. Data structures
Two records, mirroring transaction_log and object_change_log from
storage.md §14.7–14.8 so the eventual persisted form is a field-for-field subset.
// One entry per changed object within a transaction.
struct OBJECT_CHANGE_RECORD {
uint64_t objectId = 0; // memoryID (never reassigned across undo/redo — §9).
uint64_t containerMemoryId = 0; // memoryIDContainer (0 for Asset2DDefinition / root logicals).
uint64_t generatorIdBefore = 0; // memoryIDGenerator before the edit (storage.md §14.8 parent_id_before).
uint64_t generatorIdAfter = 0; // memoryIDGenerator after the edit (storage.md §14.8 parent_id_after).
uint8_t operationType = 0; // storage.md §14.8: 1=insert 2=update 4=soft_delete.
// 3=move and 8=restore are reserved; re-parenting travels via
// generatorIdBefore/After on update records.
uint8_t world = 0; // 0 = 3D geometry, 1 = 2D record, 2 = Logical object.
uint16_t objectType = 0; // VishwakarmaStorage::ObjectType for Encode/Decode dispatch.
uint64_t guardVersion = 0; // dataVersion the next traversal (undo or redo) must find on
// the live object. Written at commit as the post-edit version;
// re-stamped by every undo/redo application (§5).
// Heap-owned payload bytes (§2.5). Both null for insert/soft_delete — see §1.4.
std::byte* beforePayload = nullptr;
std::byte* afterPayload = nullptr;
uint32_t beforeSize = 0;
uint32_t afterSize = 0;
};
// One entry per user gesture.
struct TRANSACTION_RECORD {
uint64_t transactionSeq = 0; // Provisional, tab-local, monotonic. Never a real transaction_seq:
// the authority assigns those on accept. Outbox correlation handle.
uint16_t transactionKind = 1; // storage.md §14.7: 1=user_edit 3=import 5=delete ...
uint8_t outboxState = 0; // 0=solo/no session, 1=pending send, 2=sent unacked, 3=acked,
// 4=rejected. Always 0 in Phases 0-6; present so eviction honours
// the ack frontier from day one.
uint32_t commandId = 0; // Commands:: enum value, for "Undo Move" / diagnostics.
uint64_t commitTimeMs = 0; // GetTickCount64(). Display and diagnostics only, never ordering.
OBJECT_CHANGE_RECORD* changes = nullptr; // Heap-owned array, freed with its payloads.
uint32_t changeCount = 0;
uint32_t payloadBytes = 0; // Sum of before+after sizes, for the eviction budget.
};
On DATASETTAB, a fixed-slot ring in the house style (no std::vector growth in the hot path):
static constexpr uint32_t MV_MAX_UNDO_TRANSACTIONS = 128; // ConstantsApplication.h
static constexpr uint64_t MV_UNDO_PAYLOAD_BUDGET = 256ull << 20; // 256 MB per tab. ConstantsApplication.h
TRANSACTION_RECORD undoRing[MV_MAX_UNDO_TRANSACTIONS];
uint32_t undoRingHead = 0; // Next slot to write (monotonic index; physical slot = index % N).
uint32_t undoRingCount = 0; // Live entries, <= MV_MAX_UNDO_TRANSACTIONS.
uint32_t undoCursor = 0; // Entries undone but not yet re-done, counted back from head.
uint64_t undoPayloadBytes = 0;
std::atomic<bool> canUndo{ false };
std::atomic<bool> canRedo{ false };
// False when a connected network-child tab is read-only, permission-denied, or past the 24h
// offline grace period (storage.md §4-6). Always true in solo local editing; gates undo/redo
// and future edit commands uniformly (§8).
std::atomic<bool> sessionEditable{ true };
Bounds and eviction. Two independent bounds, whichever binds first: MV_MAX_UNDO_TRANSACTIONS
slots, and MV_UNDO_PAYLOAD_BUDGET. Evicting the oldest transaction delete[]s its payloads and
change array and permanently shortens the reachable history — which is correct behaviour, not an
error. Three refinements:
- The ack frontier. Once a collaboration session exists, eviction may not reclaim a
transaction whose
outboxStateis pending (1) or sent-unacked (2) — those entries are the offline work waiting to reach the server, and evicting them would silently lose it. (At minimumafterPayloadand guard metadata must survive;beforePayloadserves only undo and may be freed under budget pressure, sacrificing undo-reachability but never the outbox.) A tab that has never connected (outboxState == 0) has no frontier and evicts freely. - Oversized transactions. A single transaction larger than the whole payload budget still commits — it simply evicts everything else (subject to the ack frontier) and becomes the only reachable undo step.
- Redo discard arithmetic. When a new gesture commits while
undoCursor > 0(§2.8), the slots in[head - undoCursor, head)are freed,undoRingHead -= undoCursor,undoRingCount -= undoCursor,undoCursor = 0, and only then is the new entry written.undoPayloadBytesis adjusted at every free.
Ownership and threading. The ring is written and read only by that tab’s engineering thread.
No mutex is required for the ring itself. The UI thread never touches it; it posts
ACTION_TYPE::UNDO / REDO into todoCPUQueue like every other command, and reads the published
canUndo / canRedo atomics to grey out the ribbon buttons.
dataVersion is already present on every 3D, 2D, and Logical object. All types derive from
META_DATA, which initialises uint64_t dataVersion = 1 (डेटा.h:248). No existing data
structure needs new fields for undo/redo.
4. The chokepoint
// All four run on the engineering thread that owns the tab.
void TransactionBegin(DATASETTAB& tab, Commands commandId, uint16_t transactionKind);
void RecordObjectChange(DATASETTAB& tab, uint64_t objectId, uint8_t operationType,
VishwakarmaStorage::ObjectType objectType);
void TransactionCommit(DATASETTAB& tab); // Empty transactions are dropped, not committed.
void TransactionAbort(DATASETTAB& tab); // Modal gesture cancelled by ESC.
Timing rules, by operation:
- update (
2):RecordObjectChangeis called before the mutation, while the live object still holds its old state: it encodesbeforePayloadand capturesgeneratorIdBeforethere and then. There is no way to accidentally record a “before” that is already modified. - soft_delete (
4): called before flippingisDeleted = true(or before the loop). No payloads are stored — only the object id, type, container, andguardVersionstamped at commit. - insert (
1): called after the arena object is constructed and registered instorageObjects3D/storageObjects2D/storageLogicalObjectsunder its finalmemoryID. Because 2D objects are now allocated directly inरामby the engineering thread, theirmemoryIDis known immediately — no return-value plumbing throughEnqueueCad2D*is needed. No payloads are stored. - Calling
RecordObjectChangetwice for the sameobjectIdinside one transaction is a no-op the second time: the first capture wins, andTransactionCommitencodes the final after-state. One change record per object per transaction.
TransactionCommit walks its open change list, encodes afterPayload and generatorIdAfter for
update records from the now-mutated arena objects, stamps each record’s guardVersion with the
object’s post-edit dataVersion, commits the slot to undoRing, and refreshes canUndo /
canRedo.
Version-bump responsibility. Every update and soft-delete site must leave dataVersion
incremented before TransactionCommit runs. ModifyObjectProperty (विश्वकर्मा.cpp:934) and
TranslateSelectedSceneObjects (विश्वकर्मा.cpp:1660) already do this for 3D; Phase 3/4 adds
obj->dataVersion++ to the 2D in-place transform, asset re-parenting, and delete sites. Insert
sites already start at dataVersion = 1 from META_DATA.
Existing mutation sites and where they hook in:
| Site | File | Transaction shape |
|---|---|---|
ModifyObjectProperty |
विश्वकर्मा.cpp:908 |
1 update (3D). Cleanest site; Phase 2 wires it first. |
TranslateSelectedSceneObjects |
विश्वकर्मा.cpp:1627 |
N updates (3D placement). Phase 2. |
ApplyTransform2DToSelection (Move, Rotate) |
RenderPage2D.cpp:2712 |
N updates (2D). Phase 3. |
DeleteSelectedObjects (new) |
विश्वकर्मा.cpp + RenderPage2D.cpp |
N soft_deletes (3D geometry + 2D shapes/asset inserts). Phase 4. |
ApplyTransform2DToSelection (Copy, Offset, Mirror) |
RenderPage2D.cpp:2712 |
N inserts (2D); sources untouched. Phase 5. |
RegisterGeneratedGeometryElement |
विश्वकर्मा.cpp:801 |
1 insert per interactive 3D primitive (or part of an open import tx). Phase 5. |
CreateLogicalElement |
विश्वकर्मा.cpp:621 |
1 insert (user-triggered Folder / Page2D / Scene3D; skip initial default-tab setup). Phase 5. |
Cad2DHandleInput creation paths |
RenderPage2D.cpp:3326 |
1 insert per completed 2D shape. Phase 5. |
Cad2DInstantiateAsset |
RenderPage2D.cpp:3076 |
1 insert for the Asset2DInsert + N inserts for its member copies. Phase 5. |
Cad2DCreateAssetFromSelection |
RenderPage2D.cpp:1188 |
Mixed: inserts (definition, hidden masters, insert) + updates (memoryIDGenerator re-parent on sources). Phase 5. |
ImportStdFileIntoTab / ImportDxfFileIntoTab |
विश्वकर्मा.cpp:1890 / 1990 |
1 transaction, N inserts, begin/commit around the materialisation loop (§1.5, §6.5). Phase 6. |
Cad2DAutoGenerateDemoContent, Cad2DGenerateBulkLines, Cad2DModifyBulkLines, debug stress keys |
RenderPage2D.cpp:3548 / 3592 / 3649, विश्वकर्मा.cpp |
Excluded. Debug/benchmark scaffolding, not user data. |
5. Executing an undo
Undo pops the transaction at undoRingHead - undoCursor - 1, walks its changes in reverse
order, and applies the inverse of each (Redo walks undoRingHead - undoCursor forward):
| operationType | Undo does | Redo does |
|---|---|---|
insert (1) |
isDeleted = true, dataVersion++; 3D: push REMOVE. 2D: push HideObject (or RebuildContainerText for Text2D). |
isDeleted = false, dataVersion++; 3D: re-ADD same memoryID. 2D: Cad2DEnqueueObjectForGpu(..., false) (or RebuildContainerText). |
update (2) |
DecodeObjectPayload(beforePayload) + restore memoryIDGenerator = generatorIdBefore, dataVersion++; 3D: regenerate geometry + push MODIFY. 2D: Cad2DEnqueueObjectForGpu(..., true) (or RebuildContainerText). |
Same with afterPayload + generatorIdAfter. |
soft_delete (4) |
isDeleted = false, dataVersion++; 3D: re-ADD same memoryID. 2D: Cad2DEnqueueObjectForGpu(..., false) (or RebuildContainerText). |
isDeleted = true, dataVersion++; 3D: push REMOVE. 2D: push HideObject (or RebuildContainerText). |
Reverse order matters within a transaction: Cad2DCreateAssetFromSelection creates a definition,
hidden masters, an insert, and then re-parents source shapes onto that insert. Undoing in reverse
un-parents the source shapes before hiding the insert and definition.
The version guard, both directions. Before applying a change record (either direction),
compare the live object’s dataVersion against the record’s guardVersion. On refusal the
transaction is rejected, the user is told why, and the cursor handles the conflict per §8. On
success the apply bumps the live dataVersion (versions are history — they never decrement)
and re-stamps guardVersion with the version it just produced, which is exactly what the
opposite traversal must find. Without the re-stamp, redo would have no valid guard: undo bumps
the version, so the commit-time value could never match again. In single-user linear undo the
guard always matches by construction — locally it acts as a consistency check that catches bugs.
It becomes a live conflict gate the moment a peer connects (§8), and costs one plain integer
comparison either way.
3D apply path. Undo/redo of a 3D update decodes the payload (which includes placement) under
a brief storageObjectsMutex lock, bumps dataVersion, regenerates GeometryData via
GeometryForObject, and pushes CommandToCopyThreadType::MODIFY. Undo of a 3D insert (or redo
of delete) flips isDeleted = true and pushes REMOVE; redo of a 3D insert (or undo of delete)
flips isDeleted = false and re-pushes ADD with the same memoryID (§9).
2D apply path. Because the engineering thread owns storageObjects2D directly in राम
(§1.1), every 2D undo/redo mutates the arena object under a brief storageObjectsMutex lock and
ships the matching GPU command on the existing FIFO queue:
- Lines / Polylines / Polygons / Circles / Ellipses / Arcs:
HideObjecton soft-delete / insert-undo;Cad2DEnqueueObjectForGpu(..., isModify=false)on restore / insert-redo;Cad2DEnqueueObjectForGpu(..., isModify=true)on update. - Text2D: track dirty text containers across the transaction and call
Cad2DRebuildContainerTextForGpu(tab, container)once per affected container at the end of the transaction (not once per text object, so undoing a 5,000-text DXF import does 1 rebuild instead of 5,000). - Asset2DDefinition / Asset2DInsert: CPU-only (never drawn on GPU directly); flipping
isDeletedor decoding their payload updates CPU truth with no GPU command needed. - Batching GPU commands: an undo/redo touching N objects enqueues all 3D/2D GPU commands under one queue lock so the copy thread drains the entire undo step in a single batch without mid-undo flicker.
Bookkeeping that must follow every delete / undo-of-create:
- Remove affected IDs from 3D selection (
tab.selection) and 2D selection (selectedObjectIdsunderselection2DMutex, plusEnqueueCad2DSelectionSnapshot). - Every reader of
storageObjects3D,storageLogicalObjects, andstorageObjects2Dmust skipobj->isDeleted:- Data-tree builder (
UserInterface.cpp:1787–1806) — currently has noisDeletedfilter! - 2D hit-testing, snap candidate gathering, zoom-to-extents,
Cad2DRebuildContainerTextForGpu, and 3D snap / zoom-to-extents / properties pane (audit all in Phase 4).
- Data-tree builder (
Undo is itself a transaction, but not a logged one. An undo does not push a new entry onto the
ring; it moves undoCursor. When peers are connected the undo is published to the authority as
a synthesised forward transaction — a new update / soft_delete / restore whose payload happens to
be an older state — because the peer has no concept of our local cursor (§8). That publication
does not clear the redo stack (§2.8); only a new local gesture does.
6. Delete and restore (planned, phased)
Undo of a create requires a delete path, which does not exist yet. It is designed here and built in Phase 4.
6.1 The command. Add Commands::EDIT_DELETE (random unused 10-digit id) plus
ACTION_TYPE::DELETE_SELECTED = 30041 (alongside UNDO = 30039 and REDO = 30040, the next
free values after SNAP_SET_WORKPLANE = 30038 in UserInputProcessing.h:150), wired through the
standard 8-file ribbon recipe: ListOfCommands.h, the translation CSVs + compiled header,
AllUIControls[], an SVG icon + SVGIconManifest.h, dispatch in ProcessPendingUIActions
(Main.cpp:450), and a handler in the todoCPUQueue loop (विश्वकर्मा.cpp:2933). The Delete
key is mapped in the engineering thread’s KEYDOWN switch (विश्वकर्मा.cpp:2678) — not in
WndProc — inheriting uiKeyboardCaptureCount text-field suppression automatically. Ctrl+Z and
Ctrl+Y take the identical route using tab.isCtrlDown.
6.2 The mechanics.
- 3D: set
obj->isDeleted = true; obj->dataVersion++;, clear fromtab.selection, pushCommandToCopyThreadType::REMOVE. The copy thread handler (RenderScene3D-DirectX12.cpp:1566) already soft-deletes the page slot, releasesgpuInstanceIndexandinstanceSlotinto their fence-gated zombie queues, erasestabRes.registry.indexOfMemoryId[id], and clearshiddenInstanceMasks— leaving everything clean for a laterADDunder the samememoryID. - 2D: set
obj->isDeleted = true; obj->dataVersion++;, remove fromselectedObjectIds, pushHideObjectfor lines/curves andCad2DRebuildContainerTextForGpuonce per container with deletedText2D. GPU page compaction (RenderPage2D-DirectX12.cpp:1328) already packs out hidden runs automatically once holes reach 25% of page capacity.
6.3 Scope of v1 delete: geometry + Asset2D inserts only.
EDIT_DELETEapplies to selected 3D geometry objects and selected 2D records on the activeScene3D/Page2D.- Asset2D insert cascade: per
डेटा.h:225–229, members of a placed asset belong to their insert viamemoryIDGenerator. Deleting a selectedAsset2DInsert(or any member belonging to it) soft-deletes theAsset2DInsertand all its live members together in one transaction, leaving theAsset2DDefinitionand its hidden masters untouched so other inserts and future placements keep working. - Logical containers (
Folder,Page2D,Scene3D) are not deletable in v1: deleting a container implies cascade semantics (children, open sub-tabs, viewports) that deserve their own design pass. Linear undo never needs container deletion: a container’s children were created after it, so undo always reaches them first.
6.4 Consequence: soft-deleted objects (and superseded DynamicBlobs) accumulate. Nothing is
freed from राम until tab close. A long session of create-then-undo leaves dead objects in
World3D/World2D pages and superseded blobs in DynamicBlob pages (GPU memory is reclaimed
via page compaction and zombie-slot recycling). This is an accepted cost of the arena design,
bounded by tab close in RAM and addressed on disk by storage.md §9 lifecycle compaction
(tombstone_retained → purged_stub).
6.5 Bulk import as one transaction. Because imports are synchronous on the engineering thread
(§1.5), ImportStdFileIntoTab and ImportDxfFileIntoTab wrap their materialisation loop in one
TransactionBegin / TransactionCommit. Since an import is insert-only, its undo record carries
no payloads — only N × sizeof(OBJECT_CHANGE_RECORD). Undoing a 50,000-object DXF flips
isDeleted = true in RAM and sends one batched HideObject + (at most) one
RebuildContainerText per Page2D.
7. Solo and connected sessions: one capture path
Locked. Three options were evaluated for how much of the transaction protocol runs when no peer is connected: (A) always everything, (B) a solo fast path that skips capture, (C) always capture, defer only the network work. Option C is adopted:
- Always: full transaction capture — protobuf payloads,
generatorIdBefore/After,guardVersion, ring entry. One code path, no solo/collaborative divergence bug surface. - Only when a session exists: the outbox reader wakes up,
outboxStatestarts moving, the ack frontier constrains eviction (§3), andguardVersion+sessionEditableact as live collaboration gates (§8).
The sequence-number rule. While solo, the tab assigns transactionSeq locally and
monotonically — it is an outbox correlation handle, nothing more. The authority is the only body
that may assign real transaction_seq values (storage.md §10.1), delivered in the accept
message alongside the client’s provisional handle. Any code comparing local sequence values across
a connect boundary is wrong. Likewise, META_DATA::dataVersion starts at 1 today; when the
load/connect layer arrives it must be seeded from the persisted object_version so guards and
authority checks speak the same numbers.
8. What changes when peers connect (and network-child rules)
8.1 Remote deltas and the version guard
Walking the motivating example: a beam is at 3 m. I move it to 5 m; my client records
{objectId, update, guardVersion: 8} (the post-edit version) and publishes the transaction. A
peer moves it 5 m → 6 m; the authority commits their change as version 9 and publishes the delta,
which my client applies on the engineering thread via todoCPUQueue — without logging it to
undoRing (§2.9) and without clearing my redo stack (§2.8). I now press Ctrl+Z.
My change record expects dataVersion == 8. The live object is version 9. 9 != 8, so the
guard fires and the undo is refused. The user is told why (e.g., “Cannot undo: BEAM-104 was
changed by another user.”). Forcing 3 m would silently destroy the peer’s work; applying an
inverse delta (−2 m → 4 m) would invent an engineering dimension nobody chose or reviewed.
OPEN (Phase 7 policy choice): When the guard refuses a transaction, two cursor policies are possible:
- Skip-past (original draft): mark that transaction non-undoable and let the cursor step past it so earlier unrelated gestures stay undoable.
- Stop-at-barrier: halt undo at the conflicted transaction so an earlier gesture cannot undo underneath a peer-modified dependent object. Not needed until Phase 7 (in solo mode the guard never fails); keep the decision open until the collaboration layer lands.
When the guard passes — the common case where nobody else touched my objects — the undo is
published to the authority as an ordinary forward transaction (carrying base_object_version
and the restored state / soft_delete / restore). Peers have no notion of my local cursor; once
accepted, the undo is recorded in the shared audit trail as a normal committed change.
8.2 Network-originated actions and ID mapping
Network packets carry persistent IDs (persistedId, permanent band [2^42, 2^48) in
id.md §4 / storage.md §7.2), never another client’s session memoryID.
- On a remote
insert, this client allocates a localmemoryID = MemoryID::next(), inserts the arena object, and bindspersistedId ↔ memoryIDin the tab’s session map. - On a remote
update/soft_delete/restore, this client resolvespersistedId → local memoryID → META_DATA*and applies it on the engineering thread. - When my own local
insertis accepted by the authority, the authority assigns a permanentpersistedIdreplacing my provisional[2^40, 2^41)id (storage.md§7.2). BecauseOBJECT_CHANGE_RECORDkeys off sessionmemoryID(notpersistedId), the client updatesobj->persistedIdin place and zero entries inundoRingneed rewriting.
8.3 Operating as a network child: when undo is NOT valid
In storage.md §3, a network child is a client connected to a central .zzz model server or
subscribed to a local .yyy virtual-server host (never acting as a secondary server). Because a
network child is never authoritative, an undo is always an optimistic proposal of a forward
inverse transaction, and may be invalid for four reasons:
- Read-only / Permission denied (
storage.md§4, §6.2): If the user lacks write permission on the mounted.yyy/ folder — or permissions are revoked mid-session by the.zzzserver — undo is invalid because even an undo requires writing a new forward transaction to the authority.tab.sessionEditableflips tofalse,canUndo/canRedogrey out, and any queued undo is refused with a clear reason. - Peer modification / tombstone (
storage.md§9, §10.3): Caught locally bylive.dataVersion != guardVersion(or at the authority if the object was concurrently edited, locked, or compacted pastsoft_deletedintotombstone_retained). - Authority rejection in flight (rejection rollback): Even when local checks pass, a
synthesised undo (or any optimistic local edit) can lose a race at the authority. The rule:
when the authority rejects transaction
T, the network layer postsREJECT_TRANSACTIONtotodoCPUQueue. The engineering thread rolls backTand every later pending-local transaction in reverse order using their before-payloads, removes them from the ring, notifies the user once with the author and objects involved, and applies the authority’s published deltas. Rolling back the whole optimistic suffix avoids dependency analysis and is always correct. - Offline 24-hour grace expiry (
storage.md§5): While disconnected within the 24-hour grace period, local edits and undo/redo continue optimistically (protected from eviction by the ack frontier; undoing an unsent transaction can later be folded out by the outbox as an optimisation). Once the grace period expires (STALE - RELOAD REQUIRED),tab.sessionEditablebecomesfalseand undo/redo are blocked alongside edits until reconnect/reload.
Deferred to the collaboration work, not solved here: the outbox transport itself, 24-hour
disconnect timer mechanics, seeding dataVersion from persisted object_version on load/connect,
and the network-originated delta / REJECT_TRANSACTION queue handlers.
9. Hazards
Object identity across redo. Redo of a create (and undo of a delete) must reuse the original
memoryID, never allocate a fresh one from MemoryID::next(). Subsequent entries in the redo
stack, Asset2DInsert members (memoryIDGenerator), containers (memoryIDContainer), and
future references (id.md §3, §5) all address the original memoryID. Because arena objects are
soft-deleted in place, reusing memoryID is natural and keeps storageObjects3D /
storageObjects2D strictly sorted.
memoryIDGenerator is outside the protobuf payload. Encode* / Decode* serialize geometry
and style fields only — not memoryIDContainer or memoryIDGenerator. OBJECT_CHANGE_RECORD
must capture generatorIdBefore / generatorIdAfter explicitly, or undoing
Cad2DCreateAssetFromSelection will leave source shapes pointing at a soft-deleted
Asset2DInsert.
Asset2D transactions are multi-object and order-sensitive. Cad2DCreateAssetFromSelection
creates a definition, hidden masters, an insert, and re-parents source records in one gesture.
Undo must walk changes in strict reverse order (§5), and Phase 4 delete of an Asset2DInsert must
collect both the insert and every live member whose memoryIDGenerator == insertId.
Copy-thread ordering (and why the old 2D ingestion race is gone). Step 3B moved 2D CPU truth
onto the engineering thread, eliminating the old copy-thread CPU vector race. GPU commands still
flow over FIFO queues (commandToCopyThreadQueue for 3D, CommandToCopyThread2D queue for 2D),
so undo must push the exact GPU command matching the transition (REMOVE vs ADD vs MODIFY
in 3D; HideObject vs Upsert* vs RebuildContainerText in 2D). Pushing MODIFY for an object
already REMOVEd on the 3D copy thread is a no-op that leaves the screen stale.
The engineering thread is the sole writer, and must stay so. undoRing is lock-free precisely
because only one thread touches it. Any future network delta, permission revocation, or rejection
rollback must be posted onto todoCPUQueue, never executed from the network or extension thread.
Modal gestures and undo must not interleave. If UNDO, REDO, or DELETE_SELECTED arrives
while a modal gesture is armed or mid-flight (a 2D creation tool, 2D transform, 3D primitive
placement, or zoom-window), cancel the gesture first (TransactionAbort + existing cancel
functions, identical to ESC) and only then execute the action.
Ctrl+Z / Delete during text editing. WndProc already gates KEYDOWN on
uiKeyboardCaptureCount != 0 (Main.cpp:1370, 1410). Keep Ctrl+Z, Ctrl+Y, and Delete on the
engineering-thread KEYDOWN route (विश्वकर्मा.cpp:2678) so shortcuts can never fire while
typing in a properties field or text box.
Runtime ribbon button greying. AllUIControls[] is constexpr (UserInterface.h:559). Phase
2 must add ControlRuntimeEnabled(*ribbonTab, ctrl.action) alongside SnapControlLatched
(UserInterface.cpp:1537) so Undo/Redo visibly disable and ignore clicks when canUndo/canRedo
is false or !sessionEditable.
isDeleted ghosts across readers. The data-tree builder (UserInterface.cpp:1787–1806)
currently iterates storageLogicalObjects and storageObjects3D with no isDeleted filter.
Phase 4 must add that filter and audit 2D/3D hit-testing, snap candidate gathering,
zoom-to-extents, and Cad2DRebuildContainerTextForGpu so soft-deleted objects never appear as
ghosts, snap targets, or selection hits.
Eviction versus the outbox. Eviction (undo budget) and the ack frontier (outbox protection) must live in one function with two constraints — never simplify eviction to pure slot count, or unsent offline work will be silently dropped once the network layer arrives.
10. Implementation phases
Each phase is independently buildable and verifiable.
| Phase | Work | Verify |
|---|---|---|
| 0 | Lift the remaining 2D + Logical Encode*/Decode* out of DataStorage.cpp’s anonymous namespace (lines 247–609) into a shared DataStorageCodec.h/.cpp (or beside DataStorage.h) and expose unified EncodeObjectPayload / DecodeObjectPayload covering all 3D (delegating to existing .encode()/.decode()), 2D, and Logical types. Zero behaviour change. |
Debug x64 builds with 0 warnings; validations/yyy_roundtrip/RunRoundTrip.ps1 5/5 PASS. |
| 1 | TransactionLog.h/.cpp: OBJECT_CHANGE_RECORD (incl. generatorIdBefore/After), TRANSACTION_RECORD, fixed-slot ring + canUndo/canRedo/sessionEditable on DATASETTAB, TransactionBegin/RecordObjectChange/TransactionCommit/TransactionAbort, ExecuteUndo/ExecuteRedo, eviction + ack-frontier + redo-discard logic, tab-close ring cleanup. No call sites yet. |
Standalone unit test: commit 200 transactions into 128-slot ring; verify eviction, payload budget, ack-frontier pin, redo-branch discard, undoPayloadBytes == 0 after clear, zero leaks. |
| 2 | Wire ModifyObjectProperty (विश्वकर्मा.cpp:908) and TranslateSelectedSceneObjects (विश्वकर्मा.cpp:1627). Add Commands::EDIT_UNDO / EDIT_REDO, ACTION_TYPE::UNDO = 30039 / REDO = 30040, ribbon buttons + ControlRuntimeEnabled hook (UserInterface.cpp:1537–1610), and Ctrl+Z / Ctrl+Y in engineering-thread KEYDOWN (विश्वकर्मा.cpp:2678) with modal-tool cancel-first guard. |
Edit sphere radius in Properties Pane & move 3D selection → Ctrl+Z visibly restores and pane updates → Ctrl+Y re-applies; buttons grey at history ends; Ctrl+Z inside text field does nothing to model. |
| 3 | Wire 2D in-place transforms (Move and Rotate) in ApplyTransform2DToSelection (RenderPage2D.cpp:2712) with dataVersion++ and batched GPU re-enqueue (Upsert* / RebuildContainerText). |
Move & Rotate a mixed 2D selection (line, circle, polyline, text) → Ctrl+Z restores all in one step → Ctrl+Y re-applies. |
| 4 | Delete + restore (§6): Commands::EDIT_DELETE, ACTION_TYPE::DELETE_SELECTED = 30041, ribbon button + Delete-key mapping, DeleteSelectedObjects (3D REMOVE, 2D HideObject + RebuildContainerText, Asset2D insert+members cascade), selection cleanup, isDeleted filter in Data Tree (UserInterface.cpp:1787–1806) and all 2D/3D hit-test/snap/extents scans. |
Delete mixed 3D + 2D selection (including an Asset2D insert) → gone from screen, tree, snap, hit-test → Ctrl+Z restores all with identical memoryIDs → Ctrl+Y deletes again; .yyy round-trip 5/5 PASS. |
| 5 | Create transactions: all CREATE_* 3D primitives (RegisterGeneratedGeometryElement), user CreateLogicalElement, 2D interactive creation (Cad2DHandleInput), 2D Copy/Offset/Mirror, Cad2DInstantiateAsset, Cad2DCreateAssetFromSelection (inserts + generatorIdBefore/After updates). |
Create 3D & 2D shapes → Ctrl+Z removes → Ctrl+Y restores with identical memoryID; CreateAssetFromSelection → Ctrl+Z un-parents sources cleanly without orphans. |
| 6 | Bulk import as one transaction (§6.5): wrap ImportStdFileIntoTab (विश्वकर्मा.cpp:1890) and ImportDxfFileIntoTab (विश्वकर्मा.cpp:1990) in TransactionBegin / TransactionCommit. |
Import a DXF/STD → single Ctrl+Z clears the whole import → Ctrl+Y restores all objects cleanly. |
| 7 | Collaboration gates (deferred until network layer): live guardVersion refusal UX, outbox forward reader + synthesised undo publication, authority REJECT_TRANSACTION suffix rollback, remote-delta persistedId ↔ memoryID apply path, and sessionEditable read-only / permission / 24h-expiry gating for network children (§8). |
Two-client conflict, read-only refusal, and authority-rejection suffix-rollback tests. |
11. Explicit non-goals
Listed so each is a conscious cut rather than an oversight: persistence of the undo log across
sessions (object_undo_log stays unimplemented); the network/outbox transport itself (Phases 0–6
ship the log format, outboxState, sessionEditable, and the eviction frontier rule, with no
forward outbox reader yet); undo trees or branching history; selective / out-of-order undo of an
arbitrary older transaction (the §8 rejection rollback is LIFO suffix rollback, preserving
linearity); cross-tab undo; delete of logical containers (§6.3); merging adjacent transactions;
undo of view state, visibility, snap settings, or selection; and automatic property-level merge of
conflicting concurrent edits (storage.md §10.3).
12. Where the code changes
The complete file map for Phases 0–6 against the current codebase. “New” marks files that do not exist yet.
| File | Phase | Change |
|---|---|---|
code-core/DataStorage.cpp |
0 | Move the 3 logical + 9 2D Encode*/Decode* codecs out of the anonymous namespace (lines 247–609) and call the shared dispatcher. |
code-core/DataStorageCodec.h / .cpp — new |
0 | Shared EncodeObjectPayload / DecodeObjectPayload across all 3D (calling .encode()/.decode()), 2D, and Logical types. |
code-core/TransactionLog.h / .cpp — new |
1 | OBJECT_CHANGE_RECORD, TRANSACTION_RECORD, ring operations, chokepoint functions, undo/redo executors, eviction + ack-frontier + redo-discard logic. |
code-core/ConstantsApplication.h |
1 | MV_MAX_UNDO_TRANSACTIONS, MV_UNDO_PAYLOAD_BUDGET. |
code-core/विश्वकर्मा.h |
1 | DATASETTAB gains the ring members, canUndo/canRedo/sessionEditable atomics, and open-transaction state; ring cleanup on tab close. |
code-core/डेटा.h |
— | No change. META_DATA::dataVersion, isDeleted, memoryIDContainer, memoryIDGenerator already exist (lines 224–249) and are inherited by all 3D, 2D, and Logical types. |
code-core/RenderScene3D-DirectX12.cpp |
— | No change. The REMOVE handler (line 1566) is already complete and fence-safe; Phase 4 merely starts pushing to it. |
code-core/RenderPage2D-DirectX12.h / .cpp |
— | No change. HideObject (line 913), Upsert*, and RebuildContainerText (line 900) already handle delete, restore, and update on the 2D GPU path. |
code-core/विश्वकर्मा.cpp |
2,4,5,6 | Wire ModifyObjectProperty (908), TranslateSelectedSceneObjects (1627), RegisterGeneratedGeometryElement (801), CreateLogicalElement (621), import loops (1890, 1990); Ctrl+Z / Ctrl+Y / Delete in KEYDOWN (2678); UNDO / REDO / DELETE_SELECTED in todoCPUQueue (2933); DeleteSelectedObjects; audit 3D isDeleted scans. |
code-core/RenderPage2D.cpp |
3,4,5 | Wire ApplyTransform2DToSelection (2712), creation commits in Cad2DHandleInput (3326), Cad2DInstantiateAsset (3076), Cad2DCreateAssetFromSelection (1188); bump dataVersion++ on 2D edits/deletes; 2D delete + Asset2D insert cascade + selection cleanup; audit 2D isDeleted scans (Cad2DRebuildContainerTextForGpu, hit-test, snap, extents). |
code-core/UserInputProcessing.h |
2,4 | ACTION_TYPE::UNDO = 30039, REDO = 30040, DELETE_SELECTED = 30041 (next free values after SNAP_SET_WORKPLANE = 30038). |
code-core/ListOfCommands.h |
2,4 | Commands::EDIT_UNDO, EDIT_REDO, EDIT_DELETE (random unused 10-digit ids). |
code-core/UserInterface.h |
2,4 | AllUIControls[] entries for Undo, Redo, Delete (line 559). |
code-core/UserInterface.cpp |
2,4 | Add ControlRuntimeEnabled alongside SnapControlLatched (line 1537–1610) honouring canUndo/canRedo/sessionEditable; filter isDeleted in the data-tree builder (lines 1787–1806). |
code-miscellaneous/UserInterfaceTranslation*.csv + code-core/UserInterfaceTranslationCompiled.h/.cpp |
2,4 | New UITextIDs for Undo, Redo, Delete, and §8 refusal/rollback strings; regenerate compiled pair. |
code-core/SVGIconManifest.h + icon assets |
2,4 | Undo / Redo / Delete SVG icons. |
code-core/Main.cpp |
2,4 | ProcessPendingUIActions dispatch (line 450) for EDIT_UNDO, EDIT_REDO, EDIT_DELETE. |
13. OPEN — undo of a foreign reference, and proxy orphans
OPEN. Not settled, and an implementer must not assume either answer. Added 2026-08-27, from the
reference design in id.md §5.
A ForeignReference proxy is how one object refers to an object in another file: the referring
field holds a plain id, and for a foreign target that id names a small proxy object carrying the
target’s file alias and id (id.md §5.1, §5.3). Two properties make it an undo question rather
than an id.md question:
- A proxy is an ordinary
META_DATAobject, in the tab’sstorageLogicalObjectsdirectory. So creating one is an ordinary insert and falls under §2.1’s chokepoint rule like any other. - Proxies are shared by fan-in. One proxy serves every referrer that names the same foreign
target — ten members made from one catalogue profile share one proxy (
id.md§5.2).
The unresolved question is what an undo does with the shared object:
Authoring a foreign reference may create a proxy, or may attach to one that already exists. Undoing that gesture must remove the proxy only if no other referrer still names it — otherwise undoing one member’s profile assignment silently breaks the other nine.
Three candidate answers, none chosen:
- Never remove. Undo reverts the referring field only; the proxy is left behind. Always correct, never breaks a sibling, and leaks one small object per abandoned target. Consistent with §6.4’s already-accepted position that soft-deleted objects accumulate.
- Refcount at the proxy. Exact, and it makes undo of a create symmetric with every other insert. But it adds a mutable count to a shared object, which the transaction log then has to capture and restore like any other field — and a refcount that drifts is a use-after-free class of bug in a system that has none today.
- Scan referrers on undo. No stored state; the undo path asks whether any live object still
names the proxy. Correct and cheap at the scale where it matters (one directory scan, and
id.md§3.6 already accepts linear referrer scans), but it puts an O(n) step inside an undo.
What is already settled and constrains the answer: a repair proxy (fileAlias == 0) is
RAM-only and never persisted (id.md §5.3), so it is never part of a transaction at all — this
question concerns authored proxies only. And id.md §8 defers proxy orphan collection
generally; undo simply reaches the problem before delete does, which is why it is recorded here
rather than there.
Not blocking: nothing in Phases 0–6 creates a foreign reference, because no reference field exists
in the object model yet (id.md §3.1). This becomes live the first time one does.