|
| 1 | +# Copyright 2025 Dimensional Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import threading |
| 16 | +import time |
| 17 | + |
| 18 | +from dimos.core import In, Module, Out, rpc |
| 19 | + |
| 20 | + |
| 21 | +class Counter(Module): |
| 22 | + current_count: int = 0 |
| 23 | + |
| 24 | + count_stream: Out[int] = None |
| 25 | + |
| 26 | + def __init__(self): |
| 27 | + super().__init__() |
| 28 | + self.current_count = 0 |
| 29 | + |
| 30 | + @rpc |
| 31 | + def increment(self): |
| 32 | + """Increment the counter and publish the new value.""" |
| 33 | + self.current_count += 1 |
| 34 | + self.count_stream.publish(self.current_count) |
| 35 | + return self.current_count |
| 36 | + |
| 37 | + |
| 38 | +class CounterValidator(Module): |
| 39 | + """Calls counter.increment() as fast as possible and validates no numbers are skipped.""" |
| 40 | + |
| 41 | + count_in: In[int] = None |
| 42 | + |
| 43 | + def __init__(self, increment_func): |
| 44 | + super().__init__() |
| 45 | + self.increment_func = increment_func |
| 46 | + self.last_seen = 0 |
| 47 | + self.missing_numbers = [] |
| 48 | + self.running = False |
| 49 | + self.call_thread = None |
| 50 | + self.call_count = 0 |
| 51 | + self.total_latency = 0.0 |
| 52 | + self.call_start_time = None |
| 53 | + self.waiting_for_response = False |
| 54 | + |
| 55 | + @rpc |
| 56 | + def start(self): |
| 57 | + """Start the validator.""" |
| 58 | + self.count_in.subscribe(self._on_count_received) |
| 59 | + self.running = True |
| 60 | + self.call_thread = threading.Thread(target=self._call_loop) |
| 61 | + self.call_thread.start() |
| 62 | + |
| 63 | + @rpc |
| 64 | + def stop(self): |
| 65 | + """Stop the validator.""" |
| 66 | + self.running = False |
| 67 | + if self.call_thread: |
| 68 | + self.call_thread.join() |
| 69 | + |
| 70 | + def _on_count_received(self, count: int): |
| 71 | + """Check if we received all numbers in sequence and trigger next call.""" |
| 72 | + # Calculate round trip time |
| 73 | + if self.call_start_time: |
| 74 | + latency = time.time() - self.call_start_time |
| 75 | + self.total_latency += latency |
| 76 | + |
| 77 | + if count != self.last_seen + 1: |
| 78 | + for missing in range(self.last_seen + 1, count): |
| 79 | + self.missing_numbers.append(missing) |
| 80 | + print(f"[VALIDATOR] Missing number detected: {missing}") |
| 81 | + self.last_seen = count |
| 82 | + |
| 83 | + # Signal that we can make the next call |
| 84 | + self.waiting_for_response = False |
| 85 | + |
| 86 | + def _call_loop(self): |
| 87 | + """Call increment only after receiving response from previous call.""" |
| 88 | + while self.running: |
| 89 | + if not self.waiting_for_response: |
| 90 | + try: |
| 91 | + self.waiting_for_response = True |
| 92 | + self.call_start_time = time.time() |
| 93 | + result = self.increment_func() |
| 94 | + call_time = time.time() - self.call_start_time |
| 95 | + self.call_count += 1 |
| 96 | + if self.call_count % 100 == 0: |
| 97 | + avg_latency = ( |
| 98 | + self.total_latency / self.call_count if self.call_count > 0 else 0 |
| 99 | + ) |
| 100 | + print( |
| 101 | + f"[VALIDATOR] Made {self.call_count} calls, last result: {result}, RPC call time: {call_time * 1000:.2f}ms, avg RTT: {avg_latency * 1000:.2f}ms" |
| 102 | + ) |
| 103 | + except Exception as e: |
| 104 | + print(f"[VALIDATOR] Error calling increment: {e}") |
| 105 | + self.waiting_for_response = False |
| 106 | + time.sleep(0.001) # Small delay on error |
| 107 | + else: |
| 108 | + # Don't sleep - busy wait for maximum speed |
| 109 | + pass |
| 110 | + |
| 111 | + @rpc |
| 112 | + def get_stats(self): |
| 113 | + """Get validation statistics.""" |
| 114 | + avg_latency = self.total_latency / self.call_count if self.call_count > 0 else 0 |
| 115 | + return { |
| 116 | + "call_count": self.call_count, |
| 117 | + "last_seen": self.last_seen, |
| 118 | + "missing_count": len(self.missing_numbers), |
| 119 | + "missing_numbers": self.missing_numbers[:10] if self.missing_numbers else [], |
| 120 | + "avg_rtt_ms": avg_latency * 1000, |
| 121 | + "calls_per_sec": self.call_count / 10.0 if self.call_count > 0 else 0, |
| 122 | + } |
| 123 | + |
| 124 | + |
| 125 | +if __name__ == "__main__": |
| 126 | + import dimos.core as core |
| 127 | + from dimos.core import pLCMTransport |
| 128 | + |
| 129 | + # Start dimos with 2 workers |
| 130 | + client = core.start(2) |
| 131 | + |
| 132 | + # Deploy counter module |
| 133 | + counter = client.deploy(Counter) |
| 134 | + counter.count_stream.transport = pLCMTransport("/counter_stream") |
| 135 | + |
| 136 | + # Deploy validator module with increment function |
| 137 | + validator = client.deploy(CounterValidator, counter.increment) |
| 138 | + validator.count_in.transport = pLCMTransport("/counter_stream") |
| 139 | + |
| 140 | + # Connect validator to counter's output |
| 141 | + validator.count_in.connect(counter.count_stream) |
| 142 | + |
| 143 | + # Start modules |
| 144 | + validator.start() |
| 145 | + |
| 146 | + print("[MAIN] Counter and validator started. Running for 10 seconds...") |
| 147 | + |
| 148 | + # Test direct RPC speed for comparison |
| 149 | + print("\n[MAIN] Testing direct RPC call speed for 1 second...") |
| 150 | + start = time.time() |
| 151 | + direct_count = 0 |
| 152 | + while time.time() - start < 1.0: |
| 153 | + counter.increment() |
| 154 | + direct_count += 1 |
| 155 | + print(f"[MAIN] Direct RPC calls per second: {direct_count}") |
| 156 | + |
| 157 | + # Run for 10 seconds |
| 158 | + time.sleep(10) |
| 159 | + |
| 160 | + # Get stats before stopping |
| 161 | + stats = validator.get_stats() |
| 162 | + print(f"\n[MAIN] Final statistics:") |
| 163 | + print(f" - Total calls made: {stats['call_count']}") |
| 164 | + print(f" - Last number seen: {stats['last_seen']}") |
| 165 | + print(f" - Missing numbers: {stats['missing_count']}") |
| 166 | + print(f" - Average RTT: {stats['avg_rtt_ms']:.2f}ms") |
| 167 | + print(f" - Calls per second: {stats['calls_per_sec']:.1f}") |
| 168 | + if stats["missing_numbers"]: |
| 169 | + print(f" - First missing numbers: {stats['missing_numbers']}") |
| 170 | + |
| 171 | + # Stop modules |
| 172 | + validator.stop() |
| 173 | + |
| 174 | + # Shutdown dimos |
| 175 | + client.shutdown() |
| 176 | + |
| 177 | + print("[MAIN] Test complete.") |
0 commit comments