Software · Systems engineering
The Guardian 防双开守护
Launch the desk’s high-frequency trading engine twice by accident, and the second copy is frozen within a fifth of a second until the trader says keep it or close it. Conceived, built and tested in 70 minutes.
01System architecture
Freeze first, ask second: one watcher per trader, zero administrator rights.
The server is shared by several traders, traders work as standard users, and a standard user cannot stop a program from being born. So the design reacts instead: look ten times a second, freeze the newcomer at the operating-system level, and hand the decision to the person who clicked.
Remote Desktop session
The trader
Opens the program folder and double-clicks the terminal. Sometimes twice.
Same login · just born
Second terminal
The duplicate. Frozen within about a fifth of a second, before it can finish starting up;1 lives or dies on the trader’s answer.
Same login · already live
First terminal
The desk’s HFT engine, quoting. Recorded as instance one and never touched.
Other logins · same server
Colleagues’ terminals
Same program name, different owner. Windows will not open them for this user, so they are not counted.2
On top of every window
Yes / No prompt
Shows both copies with their start times. No is the default button.
Background · beside the clock
The Guardian
No window, no taskbar button. Polls, compares with what it knows, freezes any extra copy. 723 lines of Python.
Windows · the whole server
Process snapshot
Process id and program name for every process of every user: names only, no access implied.
Next to the program
Event log
One line per event: seen, frozen, resumed, terminated, ignored.
Simplified: the one-time path setting, the tray icon and the logon autostart are left out. Each trader who wants protection runs his own copy of the guard in his own session.
Why not just replace the shortcut with a safe launcher?
Because the terminal is not launched from a shortcut to the program. The desktop shortcut opens the program’s folder, and the terminal is double-clicked inside it. A checking launcher would be bypassed by the everyday launch route. A watcher catches every route, from any folder.
Why freeze instead of blocking the launch?
Blocking a program before it exists takes a driver or a registry launch hook, and both need administrator rights that a trader’s standard account does not have. A standard user can only act after the process is born, so the design makes that moment as short as possible: at most about a fifth of a second, against the seconds a terminal needs to start up and connect.1
Why freeze instead of killing on sight?
Sometimes a second copy is intended. A frozen copy is held, not lost: Yes resumes the very same process with no restart, No removes it. The trader stays in charge, and the safe answer is the one a stray Enter key gives.
Why does it ignore other traders?
Several traders share each server, each running his own copy of the same program. A guard that counted by name alone would take a colleague’s terminal for the first copy and freeze the trader’s own first launch. Windows already refuses to let one standard user open another user’s process, so the guard uses that refusal as its filter: if it cannot open it, it is not yours.2
02The story
One double-click too many on a live trading engine, frozen within a fifth of a second: a safeguard built in 70 minutes.
An accidental second launch of a desk’s high-frequency trading terminal is a known operational risk: two live copies under one login. After a duplicate launch on the desk, Shuo wrote the requirement on his own initiative, measured what the design needed, and released a tested safeguard 70 minutes later.3 It is deployed: installed on the desk’s trading servers.4
The Guardian sits quietly beside the clock. The first terminal runs untouched. A second one is frozen in place within about a fifth of a second,1 and a window that cannot be missed asks one question: this is already running, do you really want another? No is the default and closes the newcomer. Yes lets it carry on exactly where it stopped.5
01
The problem
A market-making desk earns its keep by posting buy and sell prices on the exchange all day. It does that through a quoting engine: a high-frequency trading terminal, built by the desk’s IT team, on servers close to the exchange. Traders reach those servers over Remote Desktop, several to a machine, each with his own login and his own copy of the terminal.
The terminal is started by double-clicking a file in a folder, so one double-click too many starts a second copy: two live engines under one login. It is a known operational risk on any trading desk, and it is an easy slip to make.
The constraints ruled out the obvious fixes:
- Standard-user rights on the server, so no system-level launch block
- Nothing could be installed, and every trader has a different install path
- A shared machine: colleagues run the same program under their own logins
- A live engine that must never be touched by mistake
02
What he built
After a duplicate launch on the desk, on his own initiative, Shuo wrote the requirement that afternoon: detect the terminal, stop a second launch, ask before letting it through, set the program’s location once per machine, start at logon, and stay out of the taskbar. Nothing like it existed on the desk.
He measured before he designed. He proved the Windows mechanism on his development machine first, then ran a short environment check in his own session on the server after the day session closed. It settled the questions the design turned on: how the terminal is actually launched, and what one look at the process list costs.
The Guardian is what those answers allowed: a background watcher that looks at the process list every 100 ms, lets the first terminal run, freezes any further copy belonging to the same trader, and asks. It is the are you sure? a double-click never had, with one difference: the thing in question is already frozen while you decide.
03
What changed
The Guardian is deployed, installed on the desk’s trading servers. With it running, an accidental second launch costs one click.4 Requirement to release took 70 minutes, including the timing run on the server, a 12-point test of the Windows mechanism and an 11-step end-to-end test passed twice.3,6
In a bank’s vocabulary this is an operational-risk control: a known human-error risk on a live trading system, closed in one afternoon with a preventive control that has a safe default and an audit trail.
It also left two things behind that later work was built on. Its slimmed, official Python runtime became the portable interpreter of CHRONOS and the DCE Level-2 Receiver,7 and its quiet-in-the-tray, starts-at-logon behavior is the pattern Shuo named as the model when he designed the Strategy Agent.
70min
from the written requirement to a tested release, the same afternoon3
≤ 0.2s
for an accidental second trading engine to be frozen in place1
100ms
between checks of every process on the server, all day: ten looks a second8
1.75ms
on average for one poll of the server’s whole process list, timed in a dry run on the trading server before the guard was written8
12/12
checks of the Windows mechanism passed before the guard was written: snapshot, suspend, resume, terminate, prompt, tray icon6
11/11
end-to-end checks passed, twice: the second time on the exact runtime that ships6
03Evidence
Ten looks a second, at a sliver of the time between them
Before writing a line of the guard, Shuo timed the polling loop where it would run: a 30-second dry run on the trading server that read the process list every 100 milliseconds, 275 times. The guard’s own way of reading the list was timed on the development PC.
One look at the process list, as a share of the 100 ms between looks
An average look on the trading server took 1.75% of the interval and the slowest of 275 about an eighth; the guard’s own native read averaged under a tenth on the development PC.
Show the dataHide the data
| Measurement | Share of the interval (%) |
|---|---|
| Trading server, fastest | 0.71% |
| Trading server, average | 1.75% |
| Trading server, slowest | 12.33% |
| Guard’s read, dev PC | 9.26% |
04Functions
Five behaviors, in the order a trader meets them
A
Set up once per machine, install nothing
Copy one folder to a trading server, point it at that machine’s terminal once, and it is on guard.
- A file picker asks once where the terminal lives on this machine; every trader’s path is different, so the path is never hard-coded
- Carries its own official Python runtime: no installer and no administrator prompt
- One more double-click makes it start at every logon
B
Out of sight until it matters
No window and no taskbar button: a shield icon in the notification area beside the clock.
- Left click: what is guarded, how many copies are running now, how many it blocked and how many the trader allowed
- Right click: status, or quit the guard
- The icon puts itself back when the Windows shell restarts or the taskbar appears late after logon
C
The freeze and the question
A second copy is stopped in place within about a fifth of a second,1 and a window on top of everything asks whether it was meant.
- The prompt names both copies with their start times and says in plain words whether the freeze succeeded
- No (the default) closes the newcomer; Yes resumes the same process and never asks about it again
- A third accidental copy is frozen at once even while the first question is still open; questions queue in launch order
D
Safe on a server it shares
It acts only on the current trader’s own copies, and only on copies it watched being born.
- A colleague’s terminal on the same server is neither counted nor touched2
- If two copies are already running when the guard starts, it warns and kills nothing: it cannot know which one holds the live session
- On exit, a copy still frozen and unanswered is closed, so nothing is left suspended forever
E
A record of every decision
Every sighting, freeze, answer and ignored process is one line in a log file beside the program.
- The guard cannot run twice itself: a second start just says it is already running
- A stop command ends it cleanly from a batch file
- The log rotates at 1 MB
05Under the hood
For the technical reader: the model, the math and the code.
The reaction-time bound, the poll loop, the design inputs, the access-check filter, the freeze path, the alternatives and the tests, with pseudo-code.
Under the hoodReaction-time bound, Win32 mechanism, measurements, test design and pseudo-code for the technical reader
No model is trained here. The Guardian is systems engineering under hard constraints: a multi-user Windows Server host reached over Remote Desktop, standard-user rights, nothing installed, and a live HFT engine one handle away. The method is the transferable part: measure before designing, derive the design from the constraints, bound the reaction time, and test the artifact that ships.
The constraint: react, because interception is not available
Refusing a launch before the process exists takes a kernel driver or an Image File Execution Options registry hook. Both need administrator rights. A standard user’s earliest possible intervention is after process creation, so the design problem becomes a bound on reaction time.
The guard runs a WM_TIMER on a never-shown top-level WS_EX_TOOLWINDOW window with a message pump (top-level so it also receives the shell’s TaskbarCreated broadcast; the tool-window style keeps it off the taskbar). Each tick takes a CreateToolhelp32Snapshot of the process table and diffs it against the set of known process ids. A duplicate born at an arbitrary moment waits for the next tick, then for the scan:
| Quantity | Value | Where measured |
|---|---|---|
| Poll interval T | 100 ms | Configuration default |
| Scan cost c, native snapshot | 9.26 ms average over 200 snapshots of 327 processes | Development machine, mechanism test |
| Poll cost, scripted dry run | 0.71 / 1.75 / 12.33 ms (min / avg / max), 275 polls in 30 s | Trading server, timed dry run |
| Share of each interval spent polling, dry run | 1.75% | Derived from the dry run |
| Design bound on τ | 100 to 200 ms | Design notes |
The poll loop: two set differences per tick
Each tick reduces the process table to the set of owned process ids and compares it with the set the guard already knows. Ids that vanished are forgotten and any handle parked for them is closed. Ids that appeared are handled oldest first, by process creation time: with nothing known, the first becomes instance one and runs free; every other newcomer goes to the freeze path.
Ordering by creation time, not by process id, decides the edge case of two copies appearing inside one 100 ms window: the older one is kept as the original and the younger one is questioned. Process ids are recycled by Windows, so an id that exits is dropped from every table the guard keeps (known, approved, pending): a later process that reuses the number is judged afresh and cannot inherit an earlier Yes.
def on_timer_tick(): # every 100 ms
mine = my_instances(target_name) # pid -> creation time, path
for pid in known - mine: # exited: forget it everywhere
forget(pid) # known, approved, pending
close_parked_handle(pid)
newcomers = sorted(mine - known, key=creation_time)
for pid in newcomers:
first_copy = (len(known) == 0)
remember(pid)
if not first_copy: # instance one runs free
freeze_and_ask(pid)Measure first: the constraints that set the design
The design was derived from constraints and measurements, not from guesses. Before the guard itself was written, Shuo proved the Windows mechanism on the development machine against a sacrificial process (12 of 12 checks), then ran a short environment check in his own session on the server after the day session closed. It confirmed the launch route and the single-process baseline, and it priced the loop with a 30-second timed dry run of 275 polls. The live terminal was never suspended or changed.
Each constraint maps to one design decision:
| Constraint or measurement | Design consequence |
|---|---|
| Standard-user account: no elevation | A watcher: no driver, no registry launch hook |
| Nothing can be installed | One self-contained folder that carries its own Python runtime |
| A shared server: several traders, each with his own login and install path | Count only the current user’s copies; ask for the path once per machine |
| Windows gives a user suspend and terminate rights over his own processes | The freeze-then-decide path needs no extra rights; proven on a sacrificial process |
| The terminal runs as one process, with no same-name helpers | Baseline count is exactly one; nothing to exempt |
| The desktop shortcut points at the program folder, not the program | A launcher shortcut would be bypassed; the watcher is the core design |
| One poll of the process list in the 30-second dry run: 1.75 ms on average | Polling at 100 ms is cheap enough to settle the design |
Ownership by access check
The snapshot lists every process on the server by name, whoever owns it. The filter is one call: OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION. For a standard user, Windows refuses that call on another user’s process, so a failed open means not mine and the process is skipped (and logged once). No token inspection, no session arithmetic, no extra rights.
Matching is on the file name, case-insensitive, not on the full path: a name match catches every launch route and every copy of the program in any folder. The configured path is used for validation, and a first instance whose real path differs from it is logged as a warning.
The guard’s own single-instance mutex and its stop event live in the Local\ namespace, which Windows scopes to one logon session, so each trader can run his own guard on the same server without blocking or stopping a colleague’s.
def my_instances(target_name):
mine = {}
for pid, name in process_snapshot(): # every process, every user
if name.lower() != target_name:
continue
handle = open_process(pid, QUERY_LIMITED_INFORMATION)
if handle is None: # access denied: another user's copy
log_once(pid, 'same name, not ours: ignored')
continue
mine[pid] = (creation_time(handle), image_path(handle))
close(handle)
return mineFreeze, ask, decide
A new owned process id while one is already known is a duplicate. It is opened with suspend, terminate and query rights and stopped with NtSuspendProcess, which suspends every thread of the process in one call. The open handle is parked in a pending table and a job goes onto a queue.
This is a two-thread producer-consumer design: the timer thread only detects and freezes, and a single worker thread drains the queue and shows MessageBoxW with MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2 | MB_TOPMOST | MB_SETFOREGROUND. The poll loop never blocks on a dialog, so a third copy is frozen on the next tick while the first question is still unanswered; questions appear one at a time in launch order. MB_DEFBUTTON2 makes No the default: a dialog that takes focus can swallow a stray Enter or Space, and that keystroke must not let a duplicate through.
def freeze_and_ask(pid): # timer thread: never blocks
handle = open_process(pid, SUSPEND_RESUME | TERMINATE | QUERY_LIMITED_INFORMATION)
if handle is None:
return # already gone on its own
frozen = suspend_process(handle) # every thread, one call
pending[pid] = handle
questions.put((pid, handle, frozen))
def prompt_worker(): # one thread: one question at a time
while True:
pid, handle, frozen = questions.get()
answer = ask_yes_no(describe(pid, frozen), default='No', topmost=True)
if answer == 'Yes':
resume_process(handle)
approved.add(pid)
else:
terminate_process(handle)
close(handle)
del pending[pid]| Situation | What the guard does |
|---|---|
| No copy known, one appears | Records it as instance one. Nothing else. |
| One copy known, another appears | Suspends the newcomer, queues the question |
| Answer: No (default) | TerminateProcess on the newcomer; counted as blocked |
| Answer: Yes | NtResumeProcess; the process id is remembered as approved and never asked about again |
| A further copy while a question is open | Suspended on the next tick; its question waits its turn |
| Guard starts and two or more copies already run | A warning only. Nothing is suspended or killed |
| A same-name process the user cannot open | Another trader’s. Ignored, logged once |
| Guard exits with a copy frozen and unanswered | That copy is terminated, so nothing stays suspended |
The obvious alternatives, and why this design instead
| Alternative | Why not |
|---|---|
| A checking launcher in place of the desktop shortcut | The real launch route is a double-click inside the program folder, so the launcher would be bypassed. Kept only as possible later hardening that would remove the sub-0.2 s gap for shortcut launches. |
| Kernel driver or registry launch hook | Blocks before birth, but needs administrator rights a trader’s standard account does not have. |
| Subscribe to process-creation events instead of polling | Polling needs no extra rights or services, and its measured cost settles the question: one poll of the server’s process list took 1.75 ms on average, under 2% of each 100 ms interval. Kernel process tracing needs administrator rights. |
| Terminate the duplicate on sight | Removes the trader’s choice. A deliberate second copy would have to be relaunched; a frozen one is resumed with no restart. |
| Match on the full path | Misses a copy started from another folder. The name catches every route; the path validates and logs. |
| Count every same-name process | On a shared server a colleague’s terminal would count as the first copy, and the trader’s own first launch would be frozen. Windows’ own access check is the filter. |
| Act on copies already running at startup | The guard cannot tell which of two running terminals holds the live session. It touches nothing it did not see being born. |
| Yes as the default button | A stray keystroke on a focus-stealing dialog would wave the duplicate through. |
Verification
Three layers, each on the thing it could reach. The Win32 mechanism was proven on the development machine against a sacrificial child process. The polling loop was timed on the server itself, where the real terminal was never suspended. The finished guard was driven end to end by a script with Notepad standing in for the terminal, using test hooks that redirect the config and log and auto-answer the dialog, and that whole run was repeated on the trimmed runtime that actually ships.
The end-to-end script is built so it cannot hurt the machine it runs on: it refuses to start if any Notepad is already open, so it never kills a window it did not create, and it asserts on live process state and on the guard’s own log, not on the guard’s word.
# scenario 1: answer No -> the duplicate dies, the first copy is untouched
guard = start_guard(auto_answer='No')
first = launch_stand_in()
check('first copy untouched', is_running(first))
second = launch_stand_in()
check('duplicate closed on No', wait_until_exited(second, timeout=6))
check('first copy still alive', is_running(first))
# scenario 5: two copies already running when the guard starts -> warn, close none
guard = start_guard(auto_answer='No') # first and third both alive
check('pre-existing copies: none closed', is_running(first) and is_running(third))
check('startup warning is in the log', log_contains('startup warning'))| Layer | What was checked | Result |
|---|---|---|
| Mechanism test | Snapshot; open, suspend, resume and terminate on a sacrificial process; topmost message box; never-shown tool window; tray icon add and remove | 12 / 12 |
| Environment check | Launch route, single-process baseline, 275 timed polls of the process list | Complete |
| End to end, development runtime | First instance untouched; duplicate killed on No; first still alive; second guard exits on the mutex; stop command; duplicate resumed on Yes; two pre-existing copies, none killed; log records the block and the startup warning | 11 / 11 |
| End to end, shipped runtime | The same 11 steps on the slimmed release runtime | 11 / 11 |
Packaging: one folder, nothing installed
The guard is 723 lines of Python standard library and ctypes: direct calls into kernel32, user32, ntdll, shell32 and comdlg32, with no third-party package. It runs under pythonw.exe, Python’s console-less interpreter, so there is no console and no taskbar button. The tray icon is a Shell_NotifyIconW icon that re-adds itself on the shell’s TaskbarCreated message. The first-run file picker is GetOpenFileNameW, because the trimmed runtime has no Tk. The settings reader accepts UTF-8 with a byte-order mark and GBK, for files edited by hand in an old Notepad.
The runtime is the official python.org build of Python 3.10.11. For this release it was cut from 42.3 MB to 27.3 MB by removing the package directory, Tcl/Tk and the unused extension libraries, then re-verified by import checks and the full end-to-end run. The whole release is a 10 MB zip: copy the folder, double-click, pick the program once.
| Failure mode | How it is engineered out |
|---|---|
| The guard is started twice | A named mutex; the second start reports and exits |
| The guard is stopped with a process frozen | Pending copies are terminated on shutdown |
| The freeze call fails | The dialog says so in plain words: suspend failed, still running |
| The shell restarts and the tray icon vanishes | The icon is re-added on the taskbar-created message and retried every tick |
| A settings file saved in the wrong encoding | Reader tolerates UTF-8 with BOM and GBK |
| The log grows without bound | Rotation at 1 MB |
| One trader’s guard interferes with another’s | Mutex and stop event are scoped to the logon session |
Built with
- Python 3.10
- ctypes (direct Win32 calls)
- Win32 API
- NT native API (
NtSuspendProcess) - Windows internals
- Windows Server
- Multi-user Remote Desktop
- Real-time process monitoring
- Multithreading (producer-consumer queue)
- Named mutex and event
- PowerShell
- Measurement before design
- Portable runtime
- Zero-install deployment
- End-to-end test automation
- Audit logging
- Fail-safe defaults
- Operational risk control
06Releases
Seventy minutes, from requirement to release.
- 16:06 · The requirementAfter the close, Shuo writes down what the guard must do: detect the terminal, stop a second launch, ask before letting it through, take the program’s location once per machine, and measure before building. Minutes later he adds: start at logon, stay off the taskbar, sit beside the clock.
- 16:31 · Mechanism provenThe Windows mechanism proven on the development machine: snapshot, suspend, resume, terminate, topmost prompt, tray icon. 12 of 12.
- 16:55 · Timed on the serverA timed dry run on the server prices the loop at 1.75 ms per poll: polling every 100 ms is cheap enough.
- 17:05 · Design adjustedThe guard will count only the current trader’s own copies, using Windows’ access check as the filter.
- 17:16 · v1.0 releasedBuilt, passed 11 of 11 end to end, runtime slimmed to 27 MB, passed 11 of 11 again on the slimmed runtime, packaged as a 10 MB zip with a user guide.
- 1Design bound: a duplicate is suspended on the first 100 ms poll after it appears, budgeted at 100 to 200 ms. The interval was not timed against the live trading terminal, and the statement that a terminal needs seconds to start and connect is a design assumption.
- 2The filter relies on standard Windows isolation between users and on the guard running without administrator rights. It was not exercised against a colleague’s live terminal.
- 3Measured from the written requirement at 16:06 to the delivered v1.0 release at 17:16 the same afternoon, in August 2026. The 70 minutes include the mechanism test, the timing run on the server and both end-to-end test runs.
- 4Version 1.0 was released in August 2026 as a self-contained folder for the desk’s trading servers, one copy per trader, and it is installed on those servers. This page reports the design, the measurements and the test results; “one click” describes the guard’s tested behavior, and no claim is made about duplicate launches caught in live use.
- 5Resuming was tested end to end with Notepad standing in for the terminal. How the trading terminal behaves after being held frozen for the seconds a decision takes was not tested.
- 6End-to-end test with Notepad standing in for the trading terminal, run once on the development runtime and once on the slimmed release runtime: 11 of 11 both times. A separate 12-point test of the Windows mechanism, on the development machine, also passed 12 of 12.
- 7The runtime is the official python.org build of Python 3.10.11 already bundled with the desk’s Spread Calculator, trimmed for this release from 42.3 MB to 27.3 MB. Later tools carry that trimmed build.
- 8100 ms is the default poll interval (configurable, minimum 50 ms). The 1.75 ms comes from a 30-second scripted dry run of the polling loop on the trading server, before the guard was written: 275 polls, 0.71 ms minimum, 1.75 ms average, 12.33 ms maximum. The guard itself reads the list through a native Windows snapshot, timed on the development machine at 9.26 ms on average over 327 processes; its own cost on the trading server was not timed separately.