Skip to content

Merge stabilisation GCR hotfixes into petri#755

Merged
tcsenpai merged 12 commits intopetrifrom
merge/stabilisation-into-petri
Apr 2, 2026
Merged

Merge stabilisation GCR hotfixes into petri#755
tcsenpai merged 12 commits intopetrifrom
merge/stabilisation-into-petri

Conversation

@tcsenpai
Copy link
Copy Markdown
Contributor

@tcsenpai tcsenpai commented Apr 2, 2026

Summary

  • Merges 9 stabilisation hotfixes into petri, most critically the GCR in-memory edit refactor and TX count inversion bug fix
  • Fixes 2 merge regressions where petri code (speculativeExecutor.ts, omniprotocol/handlers/gcr.ts) still used the old Repository-based GCR API after merge
  • Resolves docker-compose port conflicts — adopts stabilisation's staggered port scheme (RPC/Omni interleaved: 53551/53552, 53553/53554, etc.)

Stabilisation hotfixes brought in

Commit Description
979eb8c GCR in-memory edit refactor — routines now take GCRMain entity instead of Repository
628937b L2PSConsensus updated to new GCR prepareAccounts/applyTransaction API
74a4a6e TX count inversion bug fix — success/fail arrays were swapped
fdd86f0 Port staggering for devnet containers
e82ce9b Omni throughput debug merge
5dd0a9b LLM-suggested GCR cleanup fixes
b57292a Omni reconnection test fix

Petri-specific fixes (post-merge)

  • speculativeExecutor.ts — refactored to use HandleGCR.prepareAccounts() + applyTransaction() instead of direct GCRBalanceRoutines.apply(edit, repo, simulate)
  • omniprotocol/handlers/gcr.ts — loads GCRMain entity before passing to GCRIdentityRoutines.apply(), persists after success

Typecheck

  • 0 new type errors introduced (verified via diff against petri baseline)
  • 2 pre-existing errors fixed by stabilisation (omni_reconnection.ts)

Test plan

  • Verify devnet boots with new staggered port scheme
  • Run Petri consensus happy-path test to validate speculativeExecutor produces correct delta hashes
  • Confirm TX counting is correct in mempool metrics after the inversion fix
  • Integration test omni identity assign handler end-to-end

See MERGE_REPORT_stabilisation_into_petri.md in repo root for full analysis.

https://claude.ai/code/session_01WWNp94cGgFCEVWmTtE2wvV

Summary by CodeRabbit

  • Refactor

    • Restructured GCR edit processing to use batch in-memory operations instead of per-edit database calls, improving transaction processing efficiency.
    • Streamlined transaction validation and state application workflows.
  • Chores

    • Updated devnet RPC and P2P port configurations across development and test infrastructure.

cwilvx and others added 12 commits March 24, 2026 11:30
+ update gcr method names
+ clean up log.onlys
Improve Transaction Throughput
…isation-into-petri

# Conflicts:
#	testing/devnet/docker-compose.yml
…rge report

speculativeExecutor was still using the old Repository-based GCR routine
calls (GCRBalanceRoutines.apply(edit, repo, simulate)) which broke after
the stabilisation GCR refactor. Updated to use HandleGCR.prepareAccounts()
+ HandleGCR.applyTransaction() pattern consistent with all other callers.

Added MERGE_REPORT_stabilisation_into_petri.md documenting:
- All 9 stabilisation hotfixes merged
- Conflict resolutions (port staggering)
- Code adaptations needed and completed
- Follow-up action items

https://claude.ai/code/session_01WWNp94cGgFCEVWmTtE2wvV
…ge reports

omniprotocol/handlers/gcr.ts was passing Repository<GCRMain> to
GCRIdentityRoutines.apply() which now expects a GCRMain entity.
Load the entity first, pass it, and persist after successful apply.

This was the only merge-introduced type regression (verified via
diff against petri baseline — 69 pre-existing errors unchanged).

https://claude.ai/code/session_01WWNp94cGgFCEVWmTtE2wvV
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 2, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a6e8e54a-3b81-490d-99ca-c91748a0f7e6

📥 Commits

Reviewing files that changed from the base of the PR and between de41db8 and aa7663e.

📒 Files selected for processing (43)
  • .gitignore
  • MERGE_REPORT_stabilisation_into_petri.md
  • src/libs/blockchain/gcr/gcr.ts
  • src/libs/blockchain/gcr/gcr_routines/GCRBalanceRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/GCRNonceRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/ethosRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/humanpassportRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/nomisRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/pqcRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/rewardsRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/tlsnRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/udRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/utils.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/web2Routines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/xmRoutines.ts
  • src/libs/blockchain/gcr/gcr_routines/routines/zkRoutines.ts
  • src/libs/blockchain/gcr/handleGCR.ts
  • src/libs/blockchain/mempool_v2.ts
  • src/libs/blockchain/routines/Sync.ts
  • src/libs/consensus/petri/execution/speculativeExecutor.ts
  • src/libs/consensus/v2/PoRBFT.ts
  • src/libs/consensus/v2/routines/mergeMempools.ts
  • src/libs/l2ps/L2PSConsensus.ts
  • src/libs/network/endpointExecution.ts
  • src/libs/omniprotocol/protocol/handlers/gcr.ts
  • src/libs/omniprotocol/transport/PeerConnection.ts
  • src/libs/peer/routines/peerBootstrap.ts
  • testing/devnet/.env.example
  • testing/devnet/docker-compose.yml
  • testing/devnet/run-devnet
  • testing/devnet/scripts/generate-peerlist.sh
  • testing/devnet/scripts/setup.sh
  • testing/docker-compose.perf.yml
  • testing/loadgen/src/features/l2ps/shared.ts
  • testing/loadgen/src/features/omni/omni_reconnection.ts
  • testing/loadgen/src/features/omni/shared.ts
  • testing/loadgen/src/features/tlsnotary/shared.ts
  • testing/loadgen/src/token_shared.ts
  • testing/scripts/run-chaos-token-script-transfer.sh
  • testing/scripts/run-scenario.sh
  • testing/scripts/run-suite.ts
  • testing/scripts/testenv-doctor.ts

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.


Walkthrough

This PR refactors the GCR (Global Consensus Registry) application layer from a per-edit, repository-based approach with simulation flags to a transaction-level batch processing model using in-memory entity mutations. Key changes include: new batched APIs in HandleGCR (prepareAccounts, applyTransaction, applyTransactions), updated all GCR routine signatures to accept in-memory GCRMain entities instead of TypeORM repositories, revised consensus/execution paths to use batch APIs, updated devnet port configurations across test infrastructure, and supporting changes to logging and state management.

Changes

Cohort / File(s) Summary
GCR Core Refactoring
src/libs/blockchain/gcr/handleGCR.ts, src/libs/blockchain/gcr/gcr.ts
Introduced new GCRApplyResult interface, batch processing methods (prepareAccounts, applyTransaction, applyTransactions, saveGCREditChanges), and replaced single-edit apply with applyGCREdit operating on in-memory entities. Updated awardPoints to use new batch flow with prepareAccounts and applyTransaction.
GCR Routine Signature Updates
src/libs/blockchain/gcr/gcr_routines/GCRBalanceRoutines.ts, GCRNonceRoutines.ts, GCRIdentityRoutines.ts
Updated all routine apply methods to accept pre-loaded GCRMain entity instead of repository and simulate flag. Removed DB persistence logic; added new applyToEntity static methods for direct in-memory balance/nonce operations. GCRIdentityRoutines now receives accountGCR directly.
Identity Routine Handlers
src/libs/blockchain/gcr/gcr_routines/routines/ethosRoutines.ts, humanpassportRoutines.ts, nomisRoutines.ts, pqcRoutines.ts, rewardsRoutines.ts, tlsnRoutines.ts, udRoutines.ts, web2Routines.ts, xmRoutines.ts, zkRoutines.ts
Updated all identity add/remove handlers to accept accountGCR: GCRMain instead of repository/simulate parameters. Removed inline DB persistence; deferred incentive side effects into returned sideEffect async functions. Added entity to success return objects.
Utility Function Updates
src/libs/blockchain/gcr/gcr_routines/routines/utils.ts
Modified isFirstConnection to remove external repository parameter and obtain repository internally via dataSource.getRepository(GCRMain).
Consensus & Execution Integration
src/libs/consensus/petri/execution/speculativeExecutor.ts, src/libs/consensus/v2/PoRBFT.ts, src/libs/consensus/v2/routines/mergeMempools.ts, src/libs/l2ps/L2PSConsensus.ts
Refactored speculative execution and consensus routines to use new batched HandleGCR.prepareAccounts and applyTransaction APIs. Replaced per-edit loops with single batch invocation. Updated PoRBFT to use batched applyTransactions for rollback; simplified logging verbosity.
Mempool & Network Handling
src/libs/blockchain/mempool_v2.ts, src/libs/network/endpointExecution.ts
Updated mempool to track noSendBackTxs instead of incomingSet and handle duplicates via inline checking. Refactored GCR application in endpointExecution to use prepareAccounts and applyTransaction. Added consensus loop guard in mempool receive.
OmniProtocol & Sync
src/libs/omniprotocol/protocol/handlers/gcr.ts, src/libs/blockchain/routines/Sync.ts
Updated identity handler to fetch and pass accountGCR entity to routine. Replaced per-transaction GCR loop in syncGCRTables with single HandleGCR.applyTransactions call.
Devnet Port Configuration
.gitignore, testing/devnet/.env.example, testing/devnet/docker-compose.yml, testing/devnet/run-devnet, testing/devnet/scripts/generate-peerlist.sh, testing/devnet/scripts/setup.sh, testing/docker-compose.perf.yml, testing/scripts/run-chaos-token-script-transfer.sh, testing/scripts/run-suite.ts, testing/scripts/testenv-doctor.ts
Updated all RPC/HTTP and OmniProtocol P2P port assignments across devnet configs (NODE2/3/4 ports shifted); updated load test targeting, performance test defaults, and helper scripts to reflect new staggered port scheme. Added MERGE_REPORT*.md to .gitignore.
Test Infrastructure & Logging
testing/loadgen/src/features/l2ps/shared.ts, testing/loadgen/src/features/omni/omni_reconnection.ts, testing/loadgen/src/features/omni/shared.ts, testing/loadgen/src/features/tlsnotary/shared.ts, testing/loadgen/src/token_shared.ts, testing/scripts/run-scenario.sh, src/libs/omniprotocol/transport/PeerConnection.ts, src/libs/peer/routines/peerBootstrap.ts, MERGE_REPORT_stabilisation_into_petri.md
Reduced RPC wait timeouts (120s → 3s default), updated endpoint lists to match new ports, added connection state name mapping in reconnection probes. Commented out state transition validation in PeerConnection.setState. Removed process exit on peer bootstrap failure. Added merge consolidation report documenting stabilization branch integration.

Sequence Diagram

sequenceDiagram
    participant Tx as Transaction
    participant HG as HandleGCR
    participant Mem as In-Memory<br/>Cache
    participant DB as Repository
    participant SE as Side Effects

    Tx->>HG: applyTransactions([txs])
    activate HG
    
    HG->>Mem: prepareAccounts([txs])
    activate Mem
    Mem->>DB: Load GCRMain entities
    DB-->>Mem: Existing + Create entities
    Mem-->>HG: accounts Map
    deactivate Mem
    
    HG->>Mem: applyTransaction(accounts, tx, false, true)
    activate Mem
    Mem->>Mem: Clone entities (snapshot)
    Mem->>Mem: Apply GCR edits<br/>(in-memory mutations)
    Mem-->>HG: GCRApplyResult<br/>(success, entities, sideEffects)
    deactivate Mem
    
    alt applyTransaction Success
        HG->>HG: Collect sideEffects
        HG->>DB: saveGCREditChanges(accounts)
        activate DB
        DB->>DB: Persist modified entities
        DB-->>HG: Saved
        deactivate DB
        
        HG->>SE: Execute sideEffects sequentially
        activate SE
        SE->>SE: IncentiveManager calls
        SE-->>HG: Completed
        deactivate SE
    else applyTransaction Fails
        HG->>HG: Rollback (discard snapshots)
        HG-->>Tx: Failure result
    end
    
    HG-->>Tx: Success result
    deactivate HG
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~70 minutes

Possibly related PRs

  • Improve Transaction Throughput #744 — Core batch GCR refactor introducing the same HandleGCR.prepareAccounts/applyTransaction/applyTransactions APIs and updating corresponding callers across consensus, execution, and mempool paths.
  • Fixed Nomis unlinking issues #639 — Modifies GCR identity/nomis unlinking flow and IncentiveManager.nomisUnlinked integration, directly affected by this PR's identity routine signature changes.
  • Feat zk integration #662 — Adds zk-related GCR identity handlers that depend on the old repository/simulate routine signatures now refactored in this PR.

Suggested labels

refactor/gcr-batching, consensus, breaking-api-change

Suggested reviewers

  • cwilvx

Poem

🐰 ✨ Ah, what joy! In-memory batches now dance,
No more per-edit repository trance,
Snapshots and rollbacks, so clever and spry,
Side effects deferred 'til the moment is nigh,
A choir of routines, all in harmony—
The GCR now sings in sweet symphony! 🎵

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch merge/stabilisation-into-petri
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch merge/stabilisation-into-petri

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link
Copy Markdown
Contributor

Review Summary by Qodo

Merge stabilisation GCR hotfixes into petri with in-memory entity refactor and port staggering

✨ Enhancement 🐞 Bug fix

Grey Divider

Walkthroughs

Description
• **Merges 9 stabilisation hotfixes** into petri, including critical GCR in-memory edit refactor and
  TX count inversion bug fix
• **Refactors GCR API to in-memory entity pattern**: All GCR routines (HandleGCR,
  GCRBalanceRoutines, GCRIdentityRoutines, etc.) now accept pre-loaded GCRMain entities instead
  of repository parameters, enabling batch processing
• **Implements batch transaction processing**: New prepareAccounts() and applyTransaction()
  methods in HandleGCR replace per-edit database operations with deferred bulk SQL updates via
  bulkUpdateAssignedTxs()
• **Defers side effects**: Identity and rewards routines now return async sideEffect callbacks for
  execution after all edits succeed, improving transaction atomicity
• **Fixes petri merge regressions**: Updates speculativeExecutor.ts and
  omniprotocol/handlers/gcr.ts to use new unified GCR batch API
• **Resolves docker-compose port conflicts**: Adopts staggered port scheme (RPC/Omni interleaved:
  53551/53552, 53553/53554, etc.) across all test infrastructure and devnet configuration
• **Fixes 3 bugs**: TX count inversion in mempool metrics, bash array handling in test scripts,
  docker compose command syntax, and PeerConnection state transition validation
• **Improves test infrastructure**: Updates all test targets, timeouts, and port configurations to
  align with new staggered scheme; adds readable connection state names to omni reconnection tests
Diagram
flowchart LR
  A["Old Repository-based<br/>GCR API"] -->|"Refactor"| B["New In-Memory<br/>Entity Pattern"]
  B -->|"prepareAccounts()"| C["Batch Load<br/>Accounts"]
  C -->|"applyTransaction()"| D["Process All<br/>Edits In-Memory"]
  D -->|"saveGCREditChanges()"| E["Bulk Persist<br/>+ Side Effects"]
  F["Sequential Ports<br/>53551-53554"] -->|"Stagger"| G["Interleaved Ports<br/>RPC/Omni"]
  H["speculativeExecutor.ts<br/>omniprotocol/handlers/gcr.ts"] -->|"Adapt"| B
Loading

Grey Divider

File Changes

1. src/libs/blockchain/gcr/handleGCR.ts ✨ Enhancement +597/-184

GCR in-memory edit refactor with batch processing

• Refactored GCR edit application to use in-memory entity processing instead of repository-based
 operations
• Added prepareAccounts() and applyTransaction() methods for batch processing of GCR edits with
 deferred database commits
• Introduced GCRApplyResult interface and type guards (isBatchableGCREdit) for handling
 batchable edit types
• Replaced per-edit database operations with bulk SQL updates via bulkUpdateAssignedTxs() for
 efficiency
• Updated applyGCREdit() to accept GCRMain entity directly instead of repository and transaction
 parameters
• Added saveGCREditChanges() to batch-save modified entities and apply side-effects after all
 edits succeed

src/libs/blockchain/gcr/handleGCR.ts


2. src/libs/l2ps/L2PSConsensus.ts ✨ Enhancement +303/-128

L2PS consensus updated to batch GCR edit API

• Updated applyGCREdits() to use new batched prepareAccounts() and applyTransaction() API
 instead of per-edit apply() calls
• Refactored proof rollback to use batch processing with applyTransaction() and
 saveGCREditChanges()
• Replaced individual edit application loops with single batch transaction processing
• Updated mock transaction creation to include gcr_edits array in content
• Improved error handling and logging for batch operations

src/libs/l2ps/L2PSConsensus.ts


3. src/libs/network/endpointExecution.ts ✨ Enhancement +63/-58

Endpoint execution refactored for batch GCR processing

• Updated transaction execution to use new prepareAccounts() and applyTransaction() batch API
• Replaced HandleGCR.applyToTx() call with prepareAccounts() followed by applyTransaction()
• Added block scope braces to switch cases for better code organization
• Improved formatting and line wrapping for readability

src/libs/network/endpointExecution.ts


View more (39)
4. src/libs/consensus/v2/PoRBFT.ts ✨ Enhancement +45/-66

Consensus routine optimized with batched GCR processing

• Refactored applyGCREditsFromMergedMempool() to use batch processing with prepareAccounts() and
 applyTransaction()
• Added pre-filtering of already-executed transactions in single batch query via
 Chain.getExistingTransactionHashes()
• Simplified rollbackGCREditsFromTxs() to delegate to HandleGCR.applyTransactions() with
 rollback flag
• Changed return type from tuple to object with named properties for clarity
• Reduced logging verbosity by changing some log.info() calls to log.debug()

src/libs/consensus/v2/PoRBFT.ts


5. src/libs/blockchain/routines/Sync.ts ✨ Enhancement +45/-50

Sync routine updated for batch GCR processing

• Updated syncGCRTables() to use new HandleGCR.applyTransactions() batch API
• Simplified function to delegate all transaction processing to batch handler
• Improved code formatting and line wrapping consistency

src/libs/blockchain/routines/Sync.ts


6. src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts ✨ Enhancement +115/-143

Identity routines refactored to use entity-based API

• Refactored apply() method signature to accept GCRMain entity directly instead of repository
 and simulate parameters
• Updated all identity routine calls to pass entity instead of repository
• Removed repository parameter from all identity operation handlers

src/libs/blockchain/gcr/gcr_routines/GCRIdentityRoutines.ts


7. src/libs/blockchain/gcr/gcr_routines/routines/tlsnRoutines.ts ✨ Enhancement +19/-35

TLSN identity routines refactored for batch processing

• Refactored applyTLSNIdentityAdd() and applyTLSNIdentityRemove() to accept GCRMain entity
 directly
• Removed repository parameter and database save operations from function signatures
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect properties for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/tlsnRoutines.ts


8. src/libs/blockchain/gcr/gcr_routines/routines/ethosRoutines.ts ✨ Enhancement +33/-49

Ethos identity routines refactored for batch processing

• Refactored applyEthosIdentityUpsert() and applyEthosIdentityRemove() to accept GCRMain
 entity directly
• Removed repository parameter and immediate database saves
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/ethosRoutines.ts


9. src/libs/blockchain/gcr/gcr_routines/routines/humanpassportRoutines.ts ✨ Enhancement +38/-41

Human Passport identity routines refactored for batch processing

• Refactored applyHumanPassportIdentityAdd() and applyHumanPassportIdentityRemove() to accept
 GCRMain entity directly
• Removed repository parameter and immediate database saves
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/humanpassportRoutines.ts


10. src/libs/blockchain/gcr/gcr_routines/routines/nomisRoutines.ts ✨ Enhancement +27/-47

Nomis identity routines refactored for batch processing

• Refactored applyNomisIdentityUpsert() and applyNomisIdentityRemove() to accept GCRMain
 entity directly
• Removed repository parameter and immediate database saves
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/nomisRoutines.ts


11. src/libs/blockchain/gcr/gcr_routines/routines/xmRoutines.ts ✨ Enhancement +22/-32

XM identity routines refactored for batch processing

• Refactored applyXmIdentityAdd() and applyXmIdentityRemove() to accept GCRMain entity
 directly
• Removed repository parameter and immediate database saves
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/xmRoutines.ts


12. src/libs/blockchain/gcr/gcr_routines/routines/web2Routines.ts ✨ Enhancement +16/-26

Web2 identity routines refactored for batch processing

• Refactored applyWeb2IdentityAdd() and applyWeb2IdentityRemove() to accept GCRMain entity
 directly
• Removed repository parameter and immediate database saves
• Moved incentive point operations into async sideEffect callbacks
• Updated return type to include entity and sideEffect for deferred processing

src/libs/blockchain/gcr/gcr_routines/routines/web2Routines.ts


13. testing/loadgen/src/features/tlsnotary/shared.ts ⚙️ Configuration changes +1/-1

Updated TLS notary test targets to new port scheme

• Updated default localhost port targets from staggered scheme (53551/53552/53553/53554) to new
 scheme (53551/53553/53555/53557)
• Aligns with stabilisation's port staggering for RPC/Omni interleaved configuration

testing/loadgen/src/features/tlsnotary/shared.ts


14. src/libs/blockchain/gcr/gcr_routines/GCRBalanceRoutines.ts ✨ Enhancement +69/-13

GCR balance routines refactored to in-memory entity pattern

• Refactored apply() method signature to accept accountGCR: GCRMain entity instead of
 gcrMainRepository and simulate parameters
• Removed database lookup and save logic; entity is now passed pre-loaded
• Added new applyToEntity() static method for in-memory balance operations without DB persistence
• Returns modified entity in result object for batch processing workflows

src/libs/blockchain/gcr/gcr_routines/GCRBalanceRoutines.ts


15. src/libs/blockchain/gcr/gcr_routines/routines/pqcRoutines.ts ✨ Enhancement +11/-29

PQC identity routines adapted to in-memory entity API

• Updated applyPqcIdentityAdd() and applyPqcIdentityRemove() signatures to accept `accountGCR:
 GCRMain` instead of repository and simulate parameters
• Removed database save logic; entity modifications are now in-memory only
• Removed ensureGCRForUser() calls; account loading is now caller's responsibility
• Returns modified entity in result object for deferred persistence

src/libs/blockchain/gcr/gcr_routines/routines/pqcRoutines.ts


16. src/libs/blockchain/gcr/gcr_routines/routines/udRoutines.ts ✨ Enhancement +16/-31

UD identity routines refactored with deferred side effects

• Updated applyUdIdentityAdd() and applyUdIdentityRemove() to accept pre-loaded `accountGCR:
 GCRMain` entity
• Removed database persistence logic; side effects (point awards/deductions) now returned as async
 callbacks
• Refactored point award/deduction logic into sideEffect functions for deferred execution
• Returns modified entity and optional side effect function for caller to execute

src/libs/blockchain/gcr/gcr_routines/routines/udRoutines.ts


17. src/libs/consensus/petri/execution/speculativeExecutor.ts ✨ Enhancement +16/-52

Speculative executor refactored to unified GCR batch API

• Removed direct imports of individual GCR routine classes and repository dependencies
• Refactored to use unified HandleGCR.prepareAccounts() and HandleGCR.applyTransaction() API
• Simplified edit processing from per-type switch statement to single batch transaction application
• Eliminated simulate parameter; now uses in-memory batch processing pattern consistent with other
 consensus engines

src/libs/consensus/petri/execution/speculativeExecutor.ts


18. src/libs/blockchain/gcr/gcr_routines/GCRNonceRoutines.ts ✨ Enhancement +37/-13

GCR nonce routines adapted to in-memory entity pattern

• Refactored apply() method to accept accountGCR: GCRMain entity instead of repository and
 simulate parameters
• Removed database lookup and persistence logic
• Added new applyToEntity() static method for in-memory nonce operations
• Entity is now passed pre-loaded; modifications are in-memory only

src/libs/blockchain/gcr/gcr_routines/GCRNonceRoutines.ts


19. src/libs/blockchain/mempool_v2.ts 🐞 Bug fix +30/-23

Mempool transaction receive logic improved with better deduplication

• Moved consensus loop check to beginning of receive() method for early exit
• Refactored transaction deduplication logic to use Map instead of object for tracking sent-back
 transactions
• Improved error handling for duplicate key constraint violations with specific error message
 matching
• Changed log level from error to info for already-existing transactions

src/libs/blockchain/mempool_v2.ts


20. testing/loadgen/src/features/omni/omni_reconnection.ts ✨ Enhancement +8/-3

Omni reconnection test improved with readable state names

• Added import for ConnectionState type from omniprotocol transport
• Added getConnectionStateName() helper function to convert numeric connection state to string
 representation
• Updated state reporting to use human-readable state names instead of numeric values
• Improved test readability by converting connection states to named constants

testing/loadgen/src/features/omni/omni_reconnection.ts


21. src/libs/blockchain/gcr/gcr_routines/routines/rewardsRoutines.ts ✨ Enhancement +4/-21

Rewards routines refactored to in-memory entity pattern

• Updated applyAwardPoints() and applyAwardPointsRollback() signatures to accept `accountGCR:
 GCRMain` entity directly
• Removed database save logic and simulate parameter handling
• Removed ensureGCRForUser() calls; account is now passed pre-loaded
• Returns modified entity in result object for batch processing

src/libs/blockchain/gcr/gcr_routines/routines/rewardsRoutines.ts


22. testing/scripts/testenv-doctor.ts ⚙️ Configuration changes +7/-3

Test environment doctor updated with staggered port scheme

• Updated default RPC target ports from sequential (53551-53554) to staggered scheme (53551, 53553,
 53555, 53557)
• Added console logging for RPC probe results and error handling for debugging
• Aligned port configuration with new devnet port staggering scheme

testing/scripts/testenv-doctor.ts


23. testing/loadgen/src/features/l2ps/shared.ts ⚙️ Configuration changes +4/-4

L2PS test targets updated to staggered port scheme

• Updated default live targets from sequential ports (53551-53554) to staggered scheme (53551,
 53553, 53555, 53557)
• Reduced RPC and TX readiness wait timeouts from 120 seconds to 3 seconds
• Aligned port configuration with stabilisation's devnet port staggering

testing/loadgen/src/features/l2ps/shared.ts


24. testing/scripts/run-suite.ts ⚙️ Configuration changes +2/-2

Test suite targets updated to staggered port scheme

• Updated default local targets from sequential ports (53551-53554) to staggered scheme (53551,
 53553, 53555, 53557)
• Updated TARGETS environment variable default in scenario execution
• Aligned test infrastructure with new devnet port configuration

testing/scripts/run-suite.ts


25. src/libs/blockchain/gcr/gcr.ts ✨ Enhancement +7/-5

GCR utility refactored to use unified batch transaction API

• Fixed indentation alignment for ternary operator in account identifier logic
• Refactored award points transaction application to use HandleGCR.prepareAccounts() and
 HandleGCR.applyTransaction() API
• Replaced applyToTx() call with new batch account loading and unified transaction application
 pattern

src/libs/blockchain/gcr/gcr.ts


26. src/libs/omniprotocol/protocol/handlers/gcr.ts ✨ Enhancement +16/-1

Omni GCR handler adapted to in-memory entity pattern

• Added explicit account loading before calling GCRIdentityRoutines.apply() with pre-loaded entity
• Added entity persistence after successful identity operation application
• Refactored to pass accountGCR entity instead of repository to identity routine
• Ensures modified entity is saved to database after in-memory modifications

src/libs/omniprotocol/protocol/handlers/gcr.ts


27. src/libs/blockchain/gcr/gcr_routines/routines/utils.ts ✨ Enhancement +2/-1

GCR utils refactored to use injected datasource

• Added import for dataSource from datasource module
• Refactored isFirstConnection() to obtain repository from dataSource instead of accepting it as
 parameter
• Simplified function signature by removing gcrMainRepository parameter

src/libs/blockchain/gcr/gcr_routines/routines/utils.ts


28. src/libs/omniprotocol/transport/PeerConnection.ts 🐞 Bug fix +8/-8

PeerConnection state transition validation disabled

• Commented out state transition validation logic in setState() method
• Removed guard that prevented invalid connection state transitions
• Allows more permissive state transitions for reconnection scenarios

src/libs/omniprotocol/transport/PeerConnection.ts


29. testing/loadgen/src/features/omni/shared.ts ⚙️ Configuration changes +1/-1

Omni port offset adjusted for staggered port scheme

• Changed OMNI_PORT_OFFSET environment variable default from 10 to 1
• Aligns omni port derivation with new staggered port scheme where RPC and Omni ports are
 interleaved

testing/loadgen/src/features/omni/shared.ts


30. testing/loadgen/src/token_shared.ts ⚙️ Configuration changes +1/-1

Wallet address retrieval timeout reduced

• Reduced RPC readiness wait timeout from 120 seconds to 3 seconds in getWalletAddresses()
• Speeds up wallet address retrieval during test initialization

testing/loadgen/src/token_shared.ts


31. testing/scripts/run-chaos-token-script-transfer.sh ⚙️ Configuration changes +4/-4

Chaos test script targets updated to staggered port scheme

• Updated default targets from sequential ports (53551-53554) to staggered scheme (53551, 53553,
 53555, 53557)
• Updated node URL mappings for node-2, node-3, and node-4 to use new staggered ports
• Aligns chaos test infrastructure with devnet port configuration

testing/scripts/run-chaos-token-script-transfer.sh


32. testing/scripts/run-scenario.sh 🐞 Bug fix +1/-1

Bash script array handling improved for robustness

• Fixed bash array expansion syntax in for loop to handle empty EXTRA_ENV array safely
• Changed from "${EXTRA_ENV[@]}" to ${EXTRA_ENV[@]+"${EXTRA_ENV[@]}"} for proper null coalescing

testing/scripts/run-scenario.sh


33. testing/devnet/scripts/setup.sh 📝 Documentation +3/-3

Devnet setup documentation updated with staggered ports

• Updated node endpoint documentation from sequential ports (53551-53554) to staggered scheme
 (53551, 53553, 53555, 53557)
• Reflects new devnet port configuration in setup instructions

testing/devnet/scripts/setup.sh


34. testing/devnet/scripts/generate-peerlist.sh ⚙️ Configuration changes +3/-3

Peerlist generation updated to staggered port scheme

• Updated default port assignments for nodes 2, 3, and 4 from sequential (53552-53554) to staggered
 (53553, 53555, 53557)
• Aligns peerlist generation with new devnet port scheme

testing/devnet/scripts/generate-peerlist.sh


35. testing/devnet/docker-compose.yml ⚙️ Configuration changes +17/-20

Docker compose configuration updated with staggered port scheme

• Removed version: "3.8" declaration from docker-compose file
• Updated all node RPC ports from sequential (53551-53554) to staggered scheme (53551, 53553, 53555,
 53557)
• Updated all node Omni ports from sequential (53552-53555) to staggered scheme (53552, 53554,
 53556, 53558)
• Refactored port mappings to use environment variables consistently across all nodes
• Simplified OMNI_PORT configuration to use environment variables instead of hardcoded values

testing/devnet/docker-compose.yml


36. MERGE_REPORT_stabilisation_into_petri.md 📝 Documentation +106/-0

Merge report documenting stabilisation hotfixes integration

• New comprehensive merge report documenting 9 stabilisation hotfixes integrated into petri
• Details critical GCR in-memory refactor and TX count inversion bug fix
• Documents petri-specific fixes required for speculativeExecutor.ts and omni GCR handler
• Provides action plan and architectural insights for the merge

MERGE_REPORT_stabilisation_into_petri.md


37. testing/docker-compose.perf.yml ⚙️ Configuration changes +1/-1

Performance test targets updated to staggered port scheme

• Updated TARGETS environment variable from sequential ports (53551-53554) to staggered scheme
 (53551, 53553, 53555, 53557)
• Aligns performance test infrastructure with new devnet port configuration

testing/docker-compose.perf.yml


38. testing/devnet/.env.example ⚙️ Configuration changes +7/-7

Environment example updated with staggered port scheme

• Updated node RPC ports from sequential (53551-53554) to staggered scheme (53551, 53553, 53555,
 53557)
• Updated node Omni ports from sequential (53561-53564) to staggered scheme (53552, 53554, 53556,
 53558)
• Reflects new port staggering strategy for devnet configuration

testing/devnet/.env.example


39. testing/devnet/run-devnet 🐞 Bug fix +1/-1

Devnet runner command syntax corrected

• Fixed docker compose command construction by removing extra -- separator before --no-tui flag
• Corrects command syntax for proper docker compose execution

testing/devnet/run-devnet


40. src/libs/blockchain/gcr/gcr_routines/routines/zkRoutines.ts Additional files +0/-2

...

src/libs/blockchain/gcr/gcr_routines/routines/zkRoutines.ts


41. src/libs/consensus/v2/routines/mergeMempools.ts Additional files +0/-3

...

src/libs/consensus/v2/routines/mergeMempools.ts


42. src/libs/peer/routines/peerBootstrap.ts Additional files +0/-1

...

src/libs/peer/routines/peerBootstrap.ts


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown
Contributor

qodo-code-review bot commented Apr 2, 2026

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Omni creates invalid GCRMain 🐞 Bug ≡ Correctness
Description
handleIdentityAssign() creates a GCRMain with only pubkey and passes it into
GCRIdentityRoutines.apply(), which assumes required fields (e.g.,
identities/nonce/balance/assignedTxs) exist. This can throw during identity application or fail when
saving due to non-null columns lacking defaults.
Code

src/libs/omniprotocol/protocol/handlers/gcr.ts[R132-151]

+        let accountGCR = await gcrMainRepository.findOneBy({
+            pubkey: editOperation.account,
+        })
+        if (!accountGCR) {
+            accountGCR = gcrMainRepository.create({
+                pubkey: editOperation.account,
+            })
+        }
+
        // Apply the identity operation (simulate = false for actual execution)
        const result = await gcrIdentityRoutines.apply(
            editOperation,
-            gcrMainRepository,
+            accountGCR,
            false, // simulate = false (actually apply changes)
        )

+        // Persist the modified entity
+        if (result.success) {
+            await gcrMainRepository.save(accountGCR)
+        }
Evidence
The Omni handler constructs a new entity via repository.create({pubkey}) and then uses it in
identity routines and saves it on success. But the GCRMain entity defines several non-null columns
without defaults (assignedTxs, nonce, balance, identities), and HandleGCR.createAccount shows the
required initialization these fields need to be valid.

src/libs/omniprotocol/protocol/handlers/gcr.ts[128-151]
src/model/entities/GCRv2/GCR_Main.ts[12-24]
src/libs/blockchain/gcr/handleGCR.ts[1004-1065]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`handleIdentityAssign` creates a new `GCRMain` with only `pubkey`, then passes it into `GCRIdentityRoutines.apply()` and persists it. `GCRMain` has required fields without defaults, so the entity must be fully initialized before routines run and before saving.

## Issue Context
`HandleGCR.createAccount(pubkey, fillData, skipSave)` already encapsulates correct initialization for `balance`, `nonce`, `identities`, `assignedTxs`, etc.

## Fix Focus Areas
- src/libs/omniprotocol/protocol/handlers/gcr.ts[128-151]
- src/libs/blockchain/gcr/handleGCR.ts[1004-1065]

## Proposed fix
- When `findOneBy` returns null, replace `gcrMainRepository.create({ pubkey })` with `await HandleGCR.createAccount(pubkey, {}, true)` (skipSave=true), then continue applying edits.
- Keep `save(accountGCR)` after success, or alternatively call `createAccount(pubkey)` (skipSave=false) to insert immediately, then apply edits and save again if needed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Uninitialized dataSource usage 🐞 Bug ☼ Reliability
Description
HandleGCR.prepareAccounts() and saveGCREditChanges() use the exported dataSource directly, but the
repo initializes it only through Datasource.getInstance(). If these methods run before any
getInstance() call, TypeORM will throw “DataSource is not initialized” and crash transaction
simulation/consensus/sync paths.
Code

src/libs/blockchain/gcr/handleGCR.ts[R355-357]

+        // Batch load all affected GCRMain entities
+        const gcrMainRepo = dataSource.getRepository(GCRMain)
+        const gcrMainCache = new Map<string, GCRMain>()
Evidence
dataSource is exported as a new DataSource(...) and only initialized inside
Datasource.getInstance() via dataSource.initialize(). prepareAccounts() uses
dataSource.getRepository(...) without ensuring initialization, and saveGCREditChanges() does the
same when saving batched entities.

src/model/datasource.ts[39-90]
src/libs/blockchain/gcr/handleGCR.ts[332-357]
src/libs/blockchain/gcr/handleGCR.ts[609-620]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`HandleGCR.prepareAccounts()` / `saveGCREditChanges()` call `dataSource.getRepository(...)` directly. This assumes the exported `dataSource` has already been initialized, but initialization only happens via `Datasource.getInstance()`.

## Issue Context
`Datasource.getInstance()` is the codebase’s standard entrypoint that calls `dataSource.initialize()` exactly once.

## Fix Focus Areas
- src/libs/blockchain/gcr/handleGCR.ts[332-382]
- src/libs/blockchain/gcr/handleGCR.ts[609-620]
- src/model/datasource.ts[39-90]

## Proposed fix
- In both methods, replace direct `dataSource.getRepository(...)` usage with:
 - `const db = await Datasource.getInstance()`
 - `const repo = db.getDataSource().getRepository(GCRMain)`
- Alternatively, add a small internal helper like `await this.getRepositories()` (already ensures `Datasource.getInstance()`) and use that repo instead of the global export.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Rollback skips DB edits 🐞 Bug ≡ Correctness
Description
applyTransaction() decides whether to rollback based on the *failed* edit type, so a tx can perform
DB-writing edits (e.g., storageProgram) and then fail on a “batchable” edit without rolling back the
earlier DB writes. This can commit partial state for a transaction that is ultimately rejected.
Code

src/libs/blockchain/gcr/handleGCR.ts[R486-489]

+                // INFO: If on a serious run, rollback hard edits
+                if (!simulate && !this.GCRTxTypes.has(edit.type)) {
+                    await this.rollback(tx, accounts, appliedEdits)
+                }
Evidence
The rollback gate checks !this.GCRTxTypes.has(edit.type) where edit is the failing edit, not
whether any already-applied edits wrote to the DB. GCRTxTypes includes storageProgram, and
storageProgram edits persist changes via repository.save(...) when not simulating, so earlier DB
changes can remain even if the tx fails later.

src/libs/blockchain/gcr/handleGCR.ts[130-144]
src/libs/blockchain/gcr/handleGCR.ts[470-497]
src/libs/blockchain/gcr/handleGCR.ts[690-697]
src/libs/blockchain/gcr/gcr_routines/GCRStorageProgramRoutines.ts[592-639]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`applyTransaction()` currently triggers rollback only when the *failing* edit is not in `GCRTxTypes`. This can skip rollback even if earlier edits in the same tx performed DB writes.

## Issue Context
- `storageProgram` and `tlsnotary` routines can persist directly to DB when `simulate=false`.
- `appliedEdits` already tracks edits successfully applied before the failure.

## Fix Focus Areas
- src/libs/blockchain/gcr/handleGCR.ts[450-497]
- src/libs/blockchain/gcr/handleGCR.ts[130-144]

## Proposed fix
- Change the rollback condition to consider `appliedEdits`, not the failing `edit.type`, e.g.:
 - `const needsRollback = appliedEdits.some(e => !this.GCRTxTypes.has(e.type))`
 - `if (!simulate && needsRollback) await this.rollback(tx, accounts, appliedEdits)`
- Also ensure `GCRTxTypes` only contains truly in-memory/no-DB-write edit types (likely just `balance`, `nonce`, `identity`), so DB-writing types always trigger rollback when present in `appliedEdits`.
- (Stronger) Wrap per-tx application in a DB transaction for non-batchable edits so failures are atomic.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Advisory comments

4. Iterator helper dependency 🐞 Bug ⚙ Maintainability
Description
saveGCREditChanges() relies on accounts.values().toArray(), which requires runtime support for
Iterator Helpers and is not used elsewhere in the repo. Using a standard conversion (Array.from)
would avoid runtime compatibility surprises across Bun/Node environments.
Code

src/libs/blockchain/gcr/handleGCR.ts[613]

+        const entitiesToSave = accounts.values().toArray()
Evidence
This is the only .toArray() usage in the codebase, so the runtime dependency is implicit. The
devnet container runs on Bun, and standardizing the conversion would remove reliance on newer
iterator APIs.

src/libs/blockchain/gcr/handleGCR.ts[609-619]
testing/devnet/Dockerfile[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`accounts.values().toArray()` assumes iterator helper support at runtime. A standard conversion is clearer and more portable.

## Issue Context
This is the only iterator `.toArray()` usage in the repo.

## Fix Focus Areas
- src/libs/blockchain/gcr/handleGCR.ts[609-619]

## Proposed fix
Replace:
- `const entitiesToSave = accounts.values().toArray()`
with:
- `const entitiesToSave = Array.from(accounts.values())`

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@tcsenpai tcsenpai merged commit 9e8e557 into petri Apr 2, 2026
6 of 7 checks passed
@tcsenpai tcsenpai deleted the merge/stabilisation-into-petri branch April 2, 2026 16:15
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 2, 2026

Comment on lines +132 to +151
let accountGCR = await gcrMainRepository.findOneBy({
pubkey: editOperation.account,
})
if (!accountGCR) {
accountGCR = gcrMainRepository.create({
pubkey: editOperation.account,
})
}

// Apply the identity operation (simulate = false for actual execution)
const result = await gcrIdentityRoutines.apply(
editOperation,
gcrMainRepository,
accountGCR,
false, // simulate = false (actually apply changes)
)

// Persist the modified entity
if (result.success) {
await gcrMainRepository.save(accountGCR)
}
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.

Action required

1. Omni creates invalid gcrmain 🐞 Bug ≡ Correctness

handleIdentityAssign() creates a GCRMain with only pubkey and passes it into
GCRIdentityRoutines.apply(), which assumes required fields (e.g.,
identities/nonce/balance/assignedTxs) exist. This can throw during identity application or fail when
saving due to non-null columns lacking defaults.
Agent Prompt
## Issue description
`handleIdentityAssign` creates a new `GCRMain` with only `pubkey`, then passes it into `GCRIdentityRoutines.apply()` and persists it. `GCRMain` has required fields without defaults, so the entity must be fully initialized before routines run and before saving.

## Issue Context
`HandleGCR.createAccount(pubkey, fillData, skipSave)` already encapsulates correct initialization for `balance`, `nonce`, `identities`, `assignedTxs`, etc.

## Fix Focus Areas
- src/libs/omniprotocol/protocol/handlers/gcr.ts[128-151]
- src/libs/blockchain/gcr/handleGCR.ts[1004-1065]

## Proposed fix
- When `findOneBy` returns null, replace `gcrMainRepository.create({ pubkey })` with `await HandleGCR.createAccount(pubkey, {}, true)` (skipSave=true), then continue applying edits.
- Keep `save(accountGCR)` after success, or alternatively call `createAccount(pubkey)` (skipSave=false) to insert immediately, then apply edits and save again if needed.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +355 to +357
// Batch load all affected GCRMain entities
const gcrMainRepo = dataSource.getRepository(GCRMain)
const gcrMainCache = new Map<string, GCRMain>()
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.

Action required

2. Uninitialized datasource usage 🐞 Bug ☼ Reliability

HandleGCR.prepareAccounts() and saveGCREditChanges() use the exported dataSource directly, but the
repo initializes it only through Datasource.getInstance(). If these methods run before any
getInstance() call, TypeORM will throw “DataSource is not initialized” and crash transaction
simulation/consensus/sync paths.
Agent Prompt
## Issue description
`HandleGCR.prepareAccounts()` / `saveGCREditChanges()` call `dataSource.getRepository(...)` directly. This assumes the exported `dataSource` has already been initialized, but initialization only happens via `Datasource.getInstance()`.

## Issue Context
`Datasource.getInstance()` is the codebase’s standard entrypoint that calls `dataSource.initialize()` exactly once.

## Fix Focus Areas
- src/libs/blockchain/gcr/handleGCR.ts[332-382]
- src/libs/blockchain/gcr/handleGCR.ts[609-620]
- src/model/datasource.ts[39-90]

## Proposed fix
- In both methods, replace direct `dataSource.getRepository(...)` usage with:
  - `const db = await Datasource.getInstance()`
  - `const repo = db.getDataSource().getRepository(GCRMain)`
- Alternatively, add a small internal helper like `await this.getRepositories()` (already ensures `Datasource.getInstance()`) and use that repo instead of the global export.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +486 to +489
// INFO: If on a serious run, rollback hard edits
if (!simulate && !this.GCRTxTypes.has(edit.type)) {
await this.rollback(tx, accounts, appliedEdits)
}
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.

Action required

3. Rollback skips db edits 🐞 Bug ≡ Correctness

applyTransaction() decides whether to rollback based on the *failed* edit type, so a tx can perform
DB-writing edits (e.g., storageProgram) and then fail on a “batchable” edit without rolling back the
earlier DB writes. This can commit partial state for a transaction that is ultimately rejected.
Agent Prompt
## Issue description
`applyTransaction()` currently triggers rollback only when the *failing* edit is not in `GCRTxTypes`. This can skip rollback even if earlier edits in the same tx performed DB writes.

## Issue Context
- `storageProgram` and `tlsnotary` routines can persist directly to DB when `simulate=false`.
- `appliedEdits` already tracks edits successfully applied before the failure.

## Fix Focus Areas
- src/libs/blockchain/gcr/handleGCR.ts[450-497]
- src/libs/blockchain/gcr/handleGCR.ts[130-144]

## Proposed fix
- Change the rollback condition to consider `appliedEdits`, not the failing `edit.type`, e.g.:
  - `const needsRollback = appliedEdits.some(e => !this.GCRTxTypes.has(e.type))`
  - `if (!simulate && needsRollback) await this.rollback(tx, accounts, appliedEdits)`
- Also ensure `GCRTxTypes` only contains truly in-memory/no-DB-write edit types (likely just `balance`, `nonce`, `identity`), so DB-writing types always trigger rollback when present in `appliedEdits`.
- (Stronger) Wrap per-tx application in a DB transaction for non-batchable edits so failures are atomic.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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