Repository navigation
feat(pipeline): run compression and session follow-ups through observers #1639
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
Open
rohitg00
wants to merge
9
commits into
feat/iii025-s1b-observe-bindings
Choose a base branch
from
feat/iii025-s2a-observer-pipeline
base: feat/iii025-s1b-observe-bindings
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
77b1268
feat(pipeline): run compression and session follow-ups through observers
rohitg00 116dfeb
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 e9f3c43
fix(pipeline): keep the graph marker honest across failures, resets a…
rohitg00 bef4067
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 68a30f2
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 43a9920
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 31b787e
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 59bc469
Merge feat/iii025-s1b-observe-bindings into feat/iii025-s2a-observer-…
rohitg00 27b0e4d
Merge remote-tracking branch 'origin/feat/iii025-s1b-observe-bindings…
rohitg00 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
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
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
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,59 @@ | ||
| import type { IIIClient } from "iii-sdk"; | ||
| import type { StateKV } from "../state/kv.js"; | ||
| import { collectAll } from "../state/kv.js"; | ||
| import { KV } from "../state/schema.js"; | ||
| import type { CompressedObservation, Session } from "../types.js"; | ||
| import { compressMaxConcurrent, isAutoCompressEnabled } from "../config.js"; | ||
| import { needsCompression } from "./compression-state.js"; | ||
| import { logger } from "../logger.js"; | ||
| import { singleFlight } from "../runtime/recovery.js"; | ||
|
|
||
| const MAX_AGE_MS = 5 * 60_000; | ||
| const MAX_PER_RUN = 50; | ||
|
|
||
| export function createCompressionSweep(sdk: IIIClient, kv: StateKV) { | ||
| return singleFlight(async () => { | ||
| const candidates: Array<{ sessionId: string; observationId: string }> = []; | ||
| const cutoff = Date.now() - MAX_AGE_MS; | ||
| const sessions = await kv.list<Session>(KV.sessions); | ||
| for (const session of sessions) { | ||
| const observations = await collectAll<CompressedObservation>(kv, KV.observations(session.id)); | ||
| for (const obs of observations) { | ||
| if (candidates.length >= MAX_PER_RUN) break; | ||
| if (!needsCompression(obs)) continue; | ||
| if (Date.parse(obs.timestamp) > cutoff) continue; | ||
| candidates.push({ sessionId: session.id, observationId: obs.id }); | ||
| } | ||
| if (candidates.length >= MAX_PER_RUN) break; | ||
| } | ||
| const concurrency = Math.min(compressMaxConcurrent(), Math.max(1, candidates.length)); | ||
| let inFlight = 0; | ||
| let dispatched = 0; | ||
| await new Promise<void>((resolve) => { | ||
| const next = () => { | ||
| while (inFlight < concurrency && dispatched < candidates.length) { | ||
| const c = candidates[dispatched++]; | ||
| inFlight++; | ||
| sdk.trigger({ function_id: "mem::compress", payload: c }) | ||
| .catch(() => {}) | ||
| .finally(() => { inFlight--; if (dispatched >= candidates.length && inFlight === 0) resolve(); else next(); }); | ||
| } | ||
| if (dispatched >= candidates.length && inFlight === 0) resolve(); | ||
| }; | ||
| next(); | ||
| if (candidates.length === 0) resolve(); | ||
| }); | ||
| if (candidates.length > 0) logger.info("Compression sweep dispatched stale observations", { count: candidates.length }); | ||
| return { dispatched: candidates.length }; | ||
| }); | ||
| } | ||
|
|
||
| export function registerCompressionSweepFunction(sdk: IIIClient, kv: StateKV): () => Promise<{ dispatched: number }> { | ||
| const run = createCompressionSweep(sdk, kv); | ||
| sdk.registerFunction("mem::compression-sweep", () => run()); | ||
| return run; | ||
| } | ||
|
|
||
| export function compressionSweepEnabled(): boolean { | ||
| return isAutoCompressEnabled(); | ||
| } |
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,87 @@ | ||
| import type { IIIClient } from "iii-sdk"; | ||
| import { TriggerAction } from "iii-sdk"; | ||
| import type { StateKV } from "../state/kv.js"; | ||
| import { collectAll } from "../state/kv.js"; | ||
| import { KV } from "../state/schema.js"; | ||
| import type { CompressedObservation, GraphExtractMark, Memory } from "../types.js"; | ||
| import { graphExtractCooldownMs, isConsolidationEnabled, detectLlmProviderKind } from "../config.js"; | ||
| import { isReflectEnabled } from "./slots.js"; | ||
| import { logger } from "../logger.js"; | ||
| import { consolidationDue } from "../triggers/events.js"; | ||
| import { getGraphGeneration } from "../state/graph-generation.js"; | ||
|
|
||
| const graphStamp = (o: CompressedObservation): string => o.compressedAt ?? o.timestamp; | ||
|
|
||
| const fireVoid = (sdk: IIIClient, function_id: string, payload: unknown, sessionId: string) => | ||
| sdk | ||
| .trigger({ function_id, payload, action: TriggerAction.Void() }) | ||
| .catch((err) => | ||
| logger.warn(function_id + " trigger failed", { | ||
| sessionId, | ||
| error: err instanceof Error ? err.message : String(err), | ||
| }), | ||
| ); | ||
|
|
||
| export function registerPostSessionFunctions(sdk: IIIClient, kv: StateKV): void { | ||
| sdk.registerFunction("mem::post-session-graph", async (data: { sessionId: string }) => { | ||
| const stored = await kv.get<GraphExtractMark>(KV.graphExtractMarks, data.sessionId); | ||
| const graphGeneration = await getGraphGeneration(kv); | ||
| const marker = stored && (stored.graphGeneration ?? null) === graphGeneration ? stored : null; | ||
| const cooldownMs = graphExtractCooldownMs(); | ||
| if (marker && cooldownMs > 0 && Date.now() - Date.parse(marker.updatedAt) < cooldownMs) { | ||
| return { skipped: "cooldown", updatedAt: marker.updatedAt }; | ||
| } | ||
| const since = marker ? Date.parse(marker.lastObservationTimestamp) : 0; | ||
| const observations = await collectAll<CompressedObservation>(kv, KV.observations(data.sessionId)); | ||
| const fresh = observations.filter((o) => o.title && Date.parse(graphStamp(o)) > since); | ||
| if (fresh.length === 0) return { extracted: 0 }; | ||
| const result = await sdk.trigger<{ observations: CompressedObservation[] }, { success?: boolean; error?: string } | null>({ | ||
| function_id: "mem::graph-extract", | ||
| payload: { observations: fresh }, | ||
| }); | ||
| if (result?.success === false) return { extracted: 0, error: result.error ?? "graph extraction failed" }; | ||
| const maxTs = fresh.reduce((max, o) => (graphStamp(o) > max ? graphStamp(o) : max), marker?.lastObservationTimestamp ?? ""); | ||
| await kv.set(KV.graphExtractMarks, data.sessionId, { | ||
| sessionId: data.sessionId, | ||
| lastObservationTimestamp: maxTs, | ||
| extractedCount: (marker?.extractedCount ?? 0) + fresh.length, | ||
| updatedAt: new Date().toISOString(), | ||
| graphGeneration, | ||
| } satisfies GraphExtractMark); | ||
| return { extracted: fresh.length }; | ||
| }); | ||
|
|
||
| sdk.registerFunction("mem::post-session-reflect", async (data: { sessionId: string }) => { | ||
| if (!isReflectEnabled()) return { skipped: "reflect_disabled" }; | ||
| return sdk.trigger({ function_id: "mem::slot-reflect", payload: { sessionId: data.sessionId } }); | ||
| }); | ||
|
|
||
| sdk.registerFunction("mem::post-session-consolidate", async (data: { sessionId: string; skipConsolidation?: boolean }) => { | ||
| if (!isConsolidationEnabled()) return { skipped: "consolidation_disabled" }; | ||
| if (!(await consolidationDue(kv))) return { skipped: "debounced" }; | ||
| fireVoid(sdk, "mem::consolidate-pipeline", { tier: "all", force: true }, data.sessionId); | ||
| fireVoid(sdk, "mem::auto-crystallize", { olderThanDays: 0 }, data.sessionId); | ||
| if (detectLlmProviderKind() === "llm") { | ||
| fireVoid(sdk, "mem::skill-extract", { sessionId: data.sessionId }, data.sessionId); | ||
| } | ||
| return { fired: true }; | ||
| }); | ||
|
|
||
| sdk.registerFunction("mem::post-remember-graph", async (data: { input?: { content?: string; type?: string; concepts?: string[] }; output?: { success?: boolean; memory?: Memory } }) => { | ||
| const memory = data.output?.memory; | ||
| if (!data.output?.success || !memory) return { skipped: "no_memory" }; | ||
| const content = typeof data.input?.content === "string" ? data.input.content : ""; | ||
| const observation = { | ||
| id: memory.id, | ||
| title: memory.title || content.slice(0, 120) || memory.type, | ||
| narrative: content, | ||
| type: "compressed_observation", | ||
| timestamp: memory.createdAt, | ||
| sessionId: `memory:${memory.id}`, | ||
| hookType: "remember", | ||
| concepts: data.input?.concepts ?? memory.concepts ?? [], | ||
| files: memory.files ?? [], | ||
| } as unknown as CompressedObservation; | ||
| return sdk.trigger({ function_id: "mem::graph-extract", payload: { observations: [observation] } }); | ||
| }); | ||
| } | ||
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.