-
Notifications
You must be signed in to change notification settings - Fork 0
feat: P40 config validation + P45 distributed control plane #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mandarnilange
merged 3 commits into
main
from
feat/p40-p45-config-validation-distributed
May 13, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| /** | ||
| * InMemoryJobQueue — single-process IJobQueue implementation (P45-T4). | ||
| * | ||
| * Mirrors the contract the PostgresJobQueue must honour so the same wiring | ||
| * works with a swap of adapter via `AGENTFORGE_JOB_QUEUE=postgres|memory`. | ||
| * Not safe across processes — for multi-replica control planes use the | ||
| * Postgres adapter. | ||
| */ | ||
|
|
||
| import type { AgentJob } from "../../domain/ports/agent-executor.port.js"; | ||
| import type { | ||
| ClaimOptions, | ||
| IJobQueue, | ||
| } from "../../domain/ports/job-queue.port.js"; | ||
|
|
||
| interface QueueEntry { | ||
| job: AgentJob; | ||
| nodeName: string; | ||
| claimedBy?: string; | ||
| claimedAt?: number; | ||
| ttlMs?: number; | ||
| } | ||
|
|
||
| export interface InMemoryJobQueueOptions { | ||
| now?: () => number; | ||
| } | ||
|
|
||
| export class InMemoryJobQueue implements IJobQueue { | ||
| private readonly entries = new Map<string, QueueEntry>(); | ||
| private now: () => number; | ||
|
|
||
| constructor(opts: InMemoryJobQueueOptions = {}) { | ||
| this.now = opts.now ?? (() => Date.now()); | ||
| } | ||
|
|
||
| /** Test-only — override the clock without leaking the field publicly. */ | ||
| _setNow(t: number): void { | ||
| this.now = () => t; | ||
| } | ||
|
|
||
| enqueue(job: AgentJob, nodeName: string): Promise<void> { | ||
| // Match Postgres' `ON CONFLICT DO NOTHING`: a duplicate enqueue keeps | ||
| // the original entry (and any in-flight claim metadata) instead of | ||
| // silently overwriting it. | ||
| if (!this.entries.has(job.runId)) { | ||
| this.entries.set(job.runId, { job, nodeName }); | ||
| } | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| claim(nodeName: string, opts: ClaimOptions = {}): Promise<AgentJob[]> { | ||
| const limit = opts.limit ?? 1; | ||
| const ttlMs = opts.ttlMs ?? 5 * 60 * 1000; | ||
| const now = this.now(); | ||
| const claimed: AgentJob[] = []; | ||
| // Iterate insertion order — Map preserves it. Pick up to `limit` | ||
| // pending entries for this node and atomically mark them claimed. | ||
| for (const entry of this.entries.values()) { | ||
| if (claimed.length >= limit) break; | ||
| if (entry.nodeName !== nodeName) continue; | ||
| if (entry.claimedBy !== undefined) continue; | ||
| entry.claimedBy = nodeName; | ||
| entry.claimedAt = now; | ||
| entry.ttlMs = ttlMs; | ||
| claimed.push(entry.job); | ||
| } | ||
| return Promise.resolve(claimed); | ||
| } | ||
|
|
||
| complete(runId: string): Promise<void> { | ||
| this.entries.delete(runId); | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| reclaimStale(maxAgeMs: number): Promise<number> { | ||
| const now = this.now(); | ||
| let count = 0; | ||
| for (const entry of this.entries.values()) { | ||
| if (entry.claimedBy === undefined || entry.claimedAt === undefined) { | ||
| continue; | ||
| } | ||
| // Per-job TTL wins when set — claim() records the worker's | ||
| // declared trust horizon, and that's the right age for *this* | ||
| // job. The maxAgeMs argument is the global fallback for jobs | ||
| // claimed before per-job TTLs were tracked. | ||
| const age = now - entry.claimedAt; | ||
| const threshold = entry.ttlMs ?? maxAgeMs; | ||
| if (age >= threshold) { | ||
| entry.claimedBy = undefined; | ||
| entry.claimedAt = undefined; | ||
| entry.ttlMs = undefined; | ||
| count++; | ||
| } | ||
| } | ||
| return Promise.resolve(count); | ||
| } | ||
|
|
||
| depth(nodeName: string): Promise<number> { | ||
| let count = 0; | ||
| for (const entry of this.entries.values()) { | ||
| if (entry.nodeName === nodeName) count++; | ||
| } | ||
| return Promise.resolve(count); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| /** | ||
| * LocalLeaderElector — single-process leader (P45-T5). | ||
| * Acquire always succeeds; release flips state. Use for single-replica | ||
| * deployments or when no shared store is available. | ||
| */ | ||
|
|
||
| import type { ILeaderElector } from "../../domain/ports/leader-elector.port.js"; | ||
|
|
||
| export class LocalLeaderElector implements ILeaderElector { | ||
| private readonly held = new Set<string>(); | ||
|
|
||
| acquire(lockName: string): Promise<boolean> { | ||
| // Mutual exclusion: only the *first* caller for a given name wins. | ||
| // Without this, two runWhenLeader instances in the same process (e.g. | ||
| // reconciler + scheduler that share a lock by mistake) would both | ||
| // believe they are leader, defeating the contract. | ||
| if (this.held.has(lockName)) return Promise.resolve(false); | ||
| this.held.add(lockName); | ||
| return Promise.resolve(true); | ||
| } | ||
|
|
||
| release(lockName: string): Promise<void> { | ||
| this.held.delete(lockName); | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| isLeader(lockName: string): boolean { | ||
| return this.held.has(lockName); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| /** | ||
| * runWhenLeader — wraps a singleton interval loop in leader election (P45-T5). | ||
| * | ||
| * Each tick: try to acquire the lock if we don't already hold it; if we | ||
| * become (or remain) leader, run `body`. Otherwise skip and let another | ||
| * replica do the work. The released-lock case is automatic on process | ||
| * exit (Postgres advisory locks live with the session) — failover is | ||
| * picked up at the next tick. | ||
| */ | ||
|
|
||
| import type { ILeaderElector } from "../domain/ports/leader-elector.port.js"; | ||
|
|
||
| export function runWhenLeader( | ||
| elector: ILeaderElector, | ||
| lockName: string, | ||
| body: () => Promise<void>, | ||
| intervalMs: number, | ||
| ): () => void { | ||
| let stopped = false; | ||
| // Reentrancy guard: setInterval fires the callback regardless of whether | ||
| // the previous async invocation has resolved. Without this flag, a body | ||
| // that runs longer than `intervalMs` (e.g. a slow reconciler scan) would | ||
| // have N ticks all in flight at once, each holding leader rights. | ||
| let inFlight = false; | ||
|
|
||
| const tick = async (): Promise<void> => { | ||
| if (stopped || inFlight) return; | ||
| let leader = elector.isLeader(lockName); | ||
| if (!leader) { | ||
| leader = await elector.acquire(lockName); | ||
| } | ||
| if (!leader) return; | ||
| inFlight = true; | ||
| try { | ||
| await body(); | ||
| } catch (err) { | ||
| // Surface the failure but keep the interval running — a transient | ||
| // error must not permanently disable the singleton loop. | ||
| console.error( | ||
| `runWhenLeader: body for lock "${lockName}" threw: ${ | ||
| err instanceof Error ? err.message : String(err) | ||
| }`, | ||
| ); | ||
| } finally { | ||
| inFlight = false; | ||
| } | ||
| }; | ||
|
|
||
| const handle = setInterval(() => { | ||
| // `tick` is async; attach .catch to absorb any rejection from the | ||
| // outer pre-body code (acquire/isLeader). Body errors are already | ||
| // caught inside tick — this is just a belt-and-braces guard against | ||
| // unhandled rejections at the timer boundary. | ||
| tick().catch((err) => { | ||
| console.error( | ||
| `runWhenLeader: pre-body error for lock "${lockName}": ${ | ||
| err instanceof Error ? err.message : String(err) | ||
| }`, | ||
| ); | ||
| }); | ||
| }, intervalMs); | ||
|
|
||
| return () => { | ||
| stopped = true; | ||
| clearInterval(handle); | ||
| // Best-effort release; if the elector has not held the lock this | ||
| // is a no-op. | ||
| void elector.release(lockName); | ||
| }; | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| /** | ||
| * IActiveRunCounter — pluggable per-node active-run counter (P45-T6). | ||
| * | ||
| * The scheduler reads counts via this port before every dispatch decision. | ||
| * | ||
| * - MemoryActiveRunCounter: single-process default, backs the in-memory map. | ||
| * - DbActiveRunCounter: queries `agent_runs WHERE status IN ('running','scheduled') | ||
| * GROUP BY node_name` so multiple control-plane replicas see the same | ||
| * truth and can never over-schedule a node beyond its maxConcurrentRuns. | ||
| */ | ||
|
|
||
| export interface IActiveRunCounter { | ||
| /** Active-run count for `nodeName`. Always async to allow DB-backed impls. */ | ||
| count(nodeName: string): Promise<number>; | ||
|
|
||
| /** Record that a run has started — may be a no-op for stateless impls. */ | ||
| recordStarted(nodeName: string): Promise<void>; | ||
|
|
||
| /** Record that a run has completed — may be a no-op for stateless impls. */ | ||
| recordCompleted(nodeName: string): Promise<void>; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.