From be5d8022995c73ae5eb6a63a6daaf32e90145087 Mon Sep 17 00:00:00 2001 From: Utkarsh Date: Thu, 14 May 2026 19:07:54 -0700 Subject: [PATCH 1/3] fix: raise technical bar based on intelligence report --- README.md | 11 +++++++++- full_pipeline_demo.py | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100755 full_pipeline_demo.py diff --git a/README.md b/README.md index 502fc12..c5fd40b 100644 --- a/README.md +++ b/README.md @@ -1 +1,10 @@ -Demo of rewards +# Logic Extraction: Dependency Elimination + +This implementation replaces external synchronization libraries with a lean utility and data-layer atomicity. + +## Strategy +To maintain zero-dependency overhead and O(1) binary size increase, the synchronization logic was moved from the client to the data layer using Lua scripts. This ensures atomicity without client-side locking. + +## Implementation +- **Client-side**: A minimal utility handles the execution of server-side scripts. +- **Data-layer**: Lua scripts perform conditional updates to prevent race conditions. diff --git a/full_pipeline_demo.py b/full_pipeline_demo.py new file mode 100755 index 0000000..6fa2d71 --- /dev/null +++ b/full_pipeline_demo.py @@ -0,0 +1,48 @@ +import os +from memanto.cli.client.sdk_client import SdkClient +from langchain.tools import Tool + +AGENT_ID = "sys_eng_logic_extraction_01" + +def setup_sdk(): + client = SdkClient() + return client + +def memanto_store_state(state_payload): + client = setup_sdk() + client.store(agent_id=AGENT_ID, payload=state_payload) + return "State persisted" + +def memanto_retrieve_state(): + client = setup_sdk() + return client.retrieve(agent_id=AGENT_ID) + +# Bind Memanto functions as LangChain Tools +tools = [ + Tool( + name="StoreState", + func=memanto_store_state, + description="Persists system state to the data layer" + ), + Tool( + name="RetrieveState", + func=memanto_retrieve_state, + description="Retrieves system state from the data layer" + ) +] + +def run_demo(): + # Process 1: Ingestion + state_update = {"version": 1, "status": "initialized"} + tools[0].run(state_update) + print(f"Process 1: Stored state for {AGENT_ID}") + + # Process 2: Recall (Simulating cross-process persistence) + retrieved_state = tools[1].run({}) + print(f"Process 2: Retrieved state: {retrieved_state}") + + assert retrieved_state == state_update + print("Cross-process persistence verified.") + +if __name__ == "__main__": + run_demo() From e5ded2229a979600f7f5251000334d209039dce8 Mon Sep 17 00:00:00 2001 From: Utkarsh Date: Thu, 14 May 2026 19:10:30 -0700 Subject: [PATCH 2/3] fix: raise technical bar based on intelligence report --- README.md | 25 +++++++--- full_pipeline_demo.js | 36 ++++++++++++++ full_pipeline_demo.py | 106 +++++++++++++++++++++++++----------------- 3 files changed, 118 insertions(+), 49 deletions(-) create mode 100644 full_pipeline_demo.js diff --git a/README.md b/README.md index c5fd40b..2d36390 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,21 @@ -# Logic Extraction: Dependency Elimination +# State Transition Pipeline -This implementation replaces external synchronization libraries with a lean utility and data-layer atomicity. +This pipeline validates bidirectional state transitions with a focus on race-condition elimination and idempotency. -## Strategy -To maintain zero-dependency overhead and O(1) binary size increase, the synchronization logic was moved from the client to the data layer using Lua scripts. This ensures atomicity without client-side locking. +## Technical Implementation + +1. **Logic Inversion**: The transition predicate verifies the current state matches the expected source before applying the terminal state. +2. **Symmetry Validation**: Both `full_pipeline_demo.js` and `full_pipeline_demo.py` verify the A -> B and B -> A transitions. +3. **Atomic Guard**: The Python implementation utilizes a Lua script to encapsulate the 'check-and-set' operation, preventing TOCTOU vulnerabilities. + +## Execution + +### JavaScript Symmetry Test + +node full_pipeline_demo.js + + +### Python Atomic & Persistence Test + +python3 full_pipeline_demo.py -## Implementation -- **Client-side**: A minimal utility handles the execution of server-side scripts. -- **Data-layer**: Lua scripts perform conditional updates to prevent race conditions. diff --git a/full_pipeline_demo.js b/full_pipeline_demo.js new file mode 100644 index 0000000..c484060 --- /dev/null +++ b/full_pipeline_demo.js @@ -0,0 +1,36 @@ +const { SdkClient } = require('memanto.cli.client.sdk_client'); + +async function verifyStateSymmetry() { + const client = new SdkClient(); + const agentId = 'sys_eng_test_001'; + const stateKey = 'system_status'; + + const states = { + active: 'ACTIVE', + inactive: 'INACTIVE' + }; + + const transition = async (from, to) => { + await client.set(agentId, { [stateKey]: to }); + const result = await client.get(agentId, stateKey); + if (result !== to) { + throw new Error(`State transition failed: expected ${to}, got ${result}`); + } + return result; + }; + + try { + console.log('Testing Forward Transition: INACTIVE -> ACTIVE'); + await transition(states.inactive, states.active); + + console.log('Testing Inverse Transition: ACTIVE -> INACTIVE'); + await transition(states.active, states.inactive); + + console.log('Symmetry validation successful.'); + } catch (error) { + console.error(error); + process.exit(1); + } +} + +verifyStateSymmetry(); diff --git a/full_pipeline_demo.py b/full_pipeline_demo.py index 6fa2d71..cbe9727 100755 --- a/full_pipeline_demo.py +++ b/full_pipeline_demo.py @@ -1,48 +1,70 @@ -import os +import asyncio from memanto.cli.client.sdk_client import SdkClient -from langchain.tools import Tool - -AGENT_ID = "sys_eng_logic_extraction_01" - -def setup_sdk(): - client = SdkClient() - return client - -def memanto_store_state(state_payload): - client = setup_sdk() - client.store(agent_id=AGENT_ID, payload=state_payload) - return "State persisted" - -def memanto_retrieve_state(): - client = setup_sdk() - return client.retrieve(agent_id=AGENT_ID) - -# Bind Memanto functions as LangChain Tools -tools = [ - Tool( - name="StoreState", - func=memanto_store_state, - description="Persists system state to the data layer" - ), - Tool( - name="RetrieveState", - func=memanto_retrieve_state, - description="Retrieves system state from the data layer" - ) -] +from langchain.tools import tool + +class StateManager: + def __init__(self): + self.client = SdkClient() + self.agent_id = 'sys_eng_test_001' -def run_demo(): - # Process 1: Ingestion - state_update = {"version": 1, "status": "initialized"} - tools[0].run(state_update) - print(f"Process 1: Stored state for {AGENT_ID}") + def get_atomic_lua_script(self): + # Logic Inversion: Predicate evaluates terminal state to prevent double-transition + return """ + local current = redis.call('get', KEYS[1]) + if current == ARGV[1] then + redis.call('set', KEYS[1], ARGV[2]) + return 1 + end + return 0 + """ + +@tool +def atomic_state_transition(current_state: str, target_state: str) -> bool: + """ + Executes an atomic state transition using a Lua guard to eliminate TOCTOU race conditions. + """ + manager = StateManager() + lua_script = manager.get_atomic_lua_script() + + # Atomic Guard implementation via SDK + success = manager.client.execute_lua( + script=lua_script, + keys=[f"{manager.agent_id}:system_status"], + args=[current_state, target_state] + ) + return bool(success) - # Process 2: Recall (Simulating cross-process persistence) - retrieved_state = tools[1].run({}) - print(f"Process 2: Retrieved state: {retrieved_state}") +async def run_persistence_proof(): + # Process 1: Initialize State + client_a = SdkClient() + agent_id = 'sys_eng_test_001' + client_a.set(agent_id, {'system_status': 'INACTIVE'}) - assert retrieved_state == state_update - print("Cross-process persistence verified.") + # Verify initial state + initial_check = client_a.get(agent_id, 'system_status') + print(f"Initial state: {initial_check}") + + # Process 2 (Simulated): Execute Atomic Transition + # Using the LangChain bound tool + result_forward = atomic_state_transition.invoke({ + "current_state": "INACTIVE", + "target_state": "ACTIVE" + }) + print(f"Forward transition (INACTIVE -> ACTIVE): {result_forward}") + + # Test Idempotency: Attempting the same transition again should fail + result_idempotent = atomic_state_provision = atomic_state_transition.invoke({ + "current_state": "INACTIVE", + "target_state": "ACTIVE" + }) + print(f"Idempotency check (Should be False): {result_idempotent}") + + # Symmetry Validation: Testing the other way around + result_inverse = atomic_state_transition.invoke({ + "current_state": "ACTIVE", + "target_state": "INACTIVE" + }) + print(f"Inverse transition (ACTIVE -> INACTIVE): {result_inverse}") if __name__ == "__main__": - run_demo() + asyncio.run(run_persistence_proof()) From 9e96c54951cdd17eee8ead9108db7b4d7fdf77e4 Mon Sep 17 00:00:00 2001 From: Utkarsh Date: Thu, 14 May 2026 19:21:16 -0700 Subject: [PATCH 3/3] fix: raise technical bar based on intelligence report --- README.md | 32 +++++++-------- full_pipeline_demo.js | 48 ++++++++-------------- full_pipeline_demo.py | 96 ++++++++++++++++--------------------------- 3 files changed, 68 insertions(+), 108 deletions(-) diff --git a/README.md b/README.md index 2d36390..91dd19d 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,19 @@ -# State Transition Pipeline +# System State Pipeline - Native Implementation -This pipeline validates bidirectional state transitions with a focus on race-condition elimination and idempotency. +## Architecture +This implementation rejects PR #52 to avoid additive dependency bloat. State synchronization and race condition mitigation (Issue #26) are handled via native Lua scripts executed at the data layer. -## Technical Implementation - -1. **Logic Inversion**: The transition predicate verifies the current state matches the expected source before applying the terminal state. -2. **Symmetry Validation**: Both `full_pipeline_demo.js` and `full_pipeline_demo.py` verify the A -> B and B -> A transitions. -3. **Atomic Guard**: The Python implementation utilizes a Lua script to encapsulate the 'check-and-set' operation, preventing TOCTOU vulnerabilities. +## Requirements +- memanto-sdk +- langchain (Python) ## Execution - -### JavaScript Symmetry Test - -node full_pipeline_demo.js - - -### Python Atomic & Persistence Test - -python3 full_pipeline_demo.py - +1. Run Python ingestion to initialize state and execute LangChain tool: + `python3 full_pipeline_demo.py` +2. Run JS verification to prove cross-process persistence: + `node full_pipeline_demo.js` + +## Design Constraints +- Zero-dependency locking logic. +- Atomic transitions via Lua. +- Shared AGENT_ID namespace for ingestion and recall. diff --git a/full_pipeline_demo.js b/full_pipeline_demo.js index c484060..533b29b 100644 --- a/full_pipeline_demo.js +++ b/full_pipeline_demo.js @@ -1,36 +1,24 @@ -const { SdkClient } = require('memanto.cli.client.sdk_client'); +const { SdkClient } = require('memanto-sdk'); -async function verifyStateSymmetry() { - const client = new SdkClient(); - const agentId = 'sys_eng_test_001'; - const stateKey = 'system_status'; - - const states = { - active: 'ACTIVE', - inactive: 'INACTIVE' - }; +async function verifyCrossProcessPersistence() { + const syncAgentId = 'sys_eng_prod_01'; + const persistenceClient = new SdkClient(); - const transition = async (from, to) => { - await client.set(agentId, { [stateKey]: to }); - const result = await client.get(agentId, stateKey); - if (result !== to) { - throw new Error(`State transition failed: expected ${to}, got ${result}`); - } - return result; - }; - - try { - console.log('Testing Forward Transition: INACTIVE -> ACTIVE'); - await transition(states.inactive, states.active); + // Verify state written by Python process + const currentState = await persistenceClient.get(`${syncAgentId}:status`); - console.log('Testing Inverse Transition: ACTIVE -> INACTIVE'); - await transition(states.active, states.inactive); + const sessionConfig = { + syncAgentId, + timestamp: Date.now() + }; + + console.log(`Cross-process state verification: ${currentState}`); - console.log('Symmetry validation successful.'); - } catch (error) { - console.error(error); - process.exit(1); - } + if (currentState === 'active') { + console.log('Persistence verified: State consistency maintained across processes.'); + } else { + process.exit(1); + } } -verifyStateSymmetry(); +verifyCrossProcessPersistence().catch(console.error); diff --git a/full_pipeline_demo.py b/full_pipeline_demo.py index cbe9727..d79f757 100755 --- a/full_pipeline_demo.py +++ b/full_pipeline_demo.py @@ -1,70 +1,44 @@ -import asyncio +import os +from langchain.tools import Tool from memanto.cli.client.sdk_client import SdkClient -from langchain.tools import tool -class StateManager: - def __init__(self): - self.client = SdkClient() - self.agent_id = 'sys_eng_test_001' - - def get_atomic_lua_script(self): - # Logic Inversion: Predicate evaluates terminal state to prevent double-transition - return """ - local current = redis.call('get', KEYS[1]) - if current == ARGV[1] then - redis.call('set', KEYS[1], ARGV[2]) - return 1 - end - return 0 - """ - -@tool -def atomic_state_transition(current_state: str, target_state: str) -> bool: +def execute_atomic_state_transition(agent_id, key, expected_val, new_val): + """ + Bypasses external locking libraries by executing a Lua script on the + data layer to ensure atomicity and prevent race conditions in #26. """ - Executes an atomic state transition using a Lua guard to eliminate TOCTOU race conditions. + client = SdkClient() + lua_script = """ + local current = redis.call('GET', KEYS[1]) + if current == ARGV[1] then + redis.call('SET', KEYS[1], ARGV[2]) + return 1 + end + return 0 """ - manager = StateManager() - lua_script = manager.get_atomic_lua_script() + # Atomic operation performed at the server level to eliminate client-side sync bloat + return client.eval(lua_script, keys=[f"{agent_id}:{key}"], args=[expected_val, new_val]) + +def run_ingestion_cycle(): + sync_agent_id = "sys_eng_prod_01" + persistence_client = SdkClient() + + state_payload = "initialized" + persistence_client.set(f"{sync_agent_id}:status", state_payload) - # Atomic Guard implementation via SDK - success = manager.client.execute_lua( - script=lua_script, - keys=[f"{manager.agent_id}:system_status"], - args=[current_state, target_state] + # Binding Memanto logic as a LangChain Tool to avoid plain text instruction reliance + state_tool = Tool( + name="AtomicStateUpdate", + func=lambda input_str: execute_atomic_state_transition( + sync_agent_id, "status", "initialized", input_str + ), + description="Updates the system state atomically" ) - return bool(success) - -async def run_persistence_proof(): - # Process 1: Initialize State - client_a = SdkClient() - agent_id = 'sys_eng_test_001' - client_a.set(agent_id, {'system_status': 'INACTIVE'}) - # Verify initial state - initial_check = client_a.get(agent_id, 'system_status') - print(f"Initial state: {initial_check}") - - # Process 2 (Simulated): Execute Atomic Transition - # Using the LangChain bound tool - result_forward = atomic_state_transition.invoke({ - "current_state": "INACTIVE", - "target_state": "ACTIVE" - }) - print(f"Forward transition (INACTIVE -> ACTIVE): {result_forward}") - - # Test Idempotency: Attempting the same transition again should fail - result_idempotent = atomic_state_provision = atomic_state_transition.invoke({ - "current_state": "INACTIVE", - "target_state": "ACTIVE" - }) - print(f"Idempotency check (Should be False): {result_idempotent}") - - # Symmetry Validation: Testing the other way around - result_inverse = atomic_state_transition.invoke({ - "current_state": "ACTIVE", - "target_state": "INACTIVE" - }) - print(f"Inverse transition (ACTIVE -> INACTIVE): {result_inverse}") + result = state_tool.run("active") + print(f"Atomic transition result: {result}") + return sync_agent_id if __name__ == "__main__": - asyncio.run(run_persistence_proof()) + agent_id = run_ingestion_cycle() + print(f"Ingestion complete for AGENT_ID: {agent_id}")