context-epoch.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. export * as SessionContextEpoch from "./context-epoch"
  2. import { and, eq, isNull, lt, or, sql } from "drizzle-orm"
  3. import { DateTime, Effect, Schema } from "effect"
  4. import { AgentV2 } from "../agent"
  5. import type { Database } from "../database/database"
  6. import { EventV2 } from "../event"
  7. import { Location } from "../location"
  8. import { SystemContext } from "../system-context/index"
  9. import { ContextSnapshotDecodeError } from "./error"
  10. import { SessionEvent } from "./event"
  11. import { SessionInput } from "./input"
  12. import { SessionMessageID } from "./message-id"
  13. import { SessionSchema } from "./schema"
  14. import { SessionContextEpochTable, SessionTable } from "./sql"
  15. type DatabaseService = Database.Interface["db"]
  16. class RevisionMismatch extends Error {}
  17. class LocationMismatch extends Error {}
  18. export class AgentMismatch extends Error {}
  19. export class AgentReplacementBlocked extends Schema.TaggedErrorClass<AgentReplacementBlocked>()(
  20. "SessionContextEpoch.AgentReplacementBlocked",
  21. { sessionID: SessionSchema.ID, previous: AgentV2.ID, current: AgentV2.ID },
  22. ) {}
  23. const retryRevisionMismatch = <A, E>(attempt: () => Effect.Effect<A, E>): Effect.Effect<A, E> =>
  24. attempt().pipe(
  25. Effect.catchDefect((defect) =>
  26. defect instanceof RevisionMismatch
  27. ? Effect.yieldNow.pipe(Effect.andThen(retryRevisionMismatch(attempt)))
  28. : Effect.die(defect),
  29. ),
  30. )
  31. interface Prepared {
  32. readonly baseline: string
  33. readonly baselineSeq: number
  34. readonly revision: number
  35. }
  36. export function initialize(
  37. db: DatabaseService,
  38. context: Effect.Effect<SystemContext.SystemContext>,
  39. sessionID: SessionSchema.ID,
  40. location: Location.Ref,
  41. agent: AgentV2.ID,
  42. ): Effect.Effect<Prepared | undefined, SystemContext.InitializationBlocked> {
  43. return retryRevisionMismatch(() => initializeOnce(db, context, sessionID, location, agent)).pipe(
  44. Effect.withSpan("SessionContextEpoch.initialize"),
  45. )
  46. }
  47. export function prepare(
  48. db: DatabaseService,
  49. events: EventV2.Interface,
  50. context: Effect.Effect<SystemContext.SystemContext>,
  51. sessionID: SessionSchema.ID,
  52. location: Location.Ref,
  53. agent: AgentV2.ID,
  54. ): Effect.Effect<Prepared, SystemContext.InitializationBlocked | ContextSnapshotDecodeError | AgentReplacementBlocked> {
  55. return retryRevisionMismatch(() => prepareOnce(db, events, context, sessionID, location, agent)).pipe(
  56. Effect.withSpan("SessionContextEpoch.prepare"),
  57. )
  58. }
  59. const prepareOnce = Effect.fnUntraced(function* (
  60. db: DatabaseService,
  61. events: EventV2.Interface,
  62. context: Effect.Effect<SystemContext.SystemContext>,
  63. sessionID: SessionSchema.ID,
  64. location: Location.Ref,
  65. agent: AgentV2.ID,
  66. ) {
  67. const [value, stored] = yield* Effect.all([context, find(db, sessionID)], { concurrency: "unbounded" })
  68. if (!stored) {
  69. const generation = yield* SystemContext.initialize(value)
  70. const baselineSeq = yield* insert(db, sessionID, location, agent, generation)
  71. return { baseline: generation.baseline, baselineSeq, revision: 0 }
  72. }
  73. const snapshot = yield* Schema.decodeUnknownEffect(SystemContext.Snapshot)(stored.snapshot).pipe(
  74. Effect.mapError((error) => new ContextSnapshotDecodeError({ sessionID, details: String(error) })),
  75. )
  76. const replacingAgent = stored.agent !== agent
  77. const result =
  78. stored.replacement_seq === null && !replacingAgent
  79. ? yield* SystemContext.reconcile(value, snapshot)
  80. : yield* SystemContext.replace(value, snapshot)
  81. if (result._tag === "ReplacementBlocked" && replacingAgent) {
  82. yield* fence(db, sessionID, agent, stored.revision)
  83. return yield* new AgentReplacementBlocked({ sessionID, previous: stored.agent, current: agent })
  84. }
  85. if (result._tag === "Unchanged" || result._tag === "ReplacementBlocked") {
  86. yield* fence(db, sessionID, agent, stored.revision)
  87. return { baseline: stored.baseline, baselineSeq: stored.baseline_seq, revision: stored.revision }
  88. }
  89. if (result._tag === "ReplacementReady") {
  90. const replacementSeq = stored.replacement_seq ?? (yield* SessionInput.latestSeq(db, sessionID))
  91. yield* replace(db, sessionID, agent, stored.revision, replacementSeq, result.generation)
  92. return { baseline: result.generation.baseline, baselineSeq: replacementSeq, revision: stored.revision + 1 }
  93. }
  94. yield* events.publish(
  95. SessionEvent.ContextUpdated,
  96. { sessionID, messageID: SessionMessageID.ID.create(), timestamp: yield* DateTime.now, text: result.text },
  97. { commit: () => advance(db, sessionID, stored.revision, result.snapshot).pipe(Effect.orDie) },
  98. )
  99. return { baseline: stored.baseline, baselineSeq: stored.baseline_seq, revision: stored.revision + 1 }
  100. })
  101. const initializeOnce = Effect.fnUntraced(function* (
  102. db: DatabaseService,
  103. context: Effect.Effect<SystemContext.SystemContext>,
  104. sessionID: SessionSchema.ID,
  105. location: Location.Ref,
  106. agent: AgentV2.ID,
  107. ) {
  108. if (yield* exists(db, sessionID)) return
  109. const generation = yield* context.pipe(Effect.flatMap(SystemContext.initialize))
  110. const baselineSeq = yield* insert(db, sessionID, location, agent, generation)
  111. return { baseline: generation.baseline, baselineSeq, revision: 0 }
  112. })
  113. const exists = Effect.fn("SessionContextEpoch.exists")(function* (db: DatabaseService, sessionID: SessionSchema.ID) {
  114. return (
  115. (yield* db
  116. .select({ sessionID: SessionContextEpochTable.session_id })
  117. .from(SessionContextEpochTable)
  118. .where(eq(SessionContextEpochTable.session_id, sessionID))
  119. .get()
  120. .pipe(Effect.orDie)) !== undefined
  121. )
  122. })
  123. const find = Effect.fn("SessionContextEpoch.find")(function* (db: DatabaseService, sessionID: SessionSchema.ID) {
  124. return yield* db
  125. .select()
  126. .from(SessionContextEpochTable)
  127. .where(eq(SessionContextEpochTable.session_id, sessionID))
  128. .get()
  129. .pipe(Effect.orDie)
  130. })
  131. const requireAgentSelection = Effect.fnUntraced(function* (
  132. db: DatabaseService,
  133. sessionID: SessionSchema.ID,
  134. agent: AgentV2.ID,
  135. ) {
  136. const selected = yield* db
  137. .select({ agent: SessionTable.agent })
  138. .from(SessionTable)
  139. .where(eq(SessionTable.id, sessionID))
  140. .get()
  141. .pipe(Effect.orDie)
  142. if (!selected || (selected.agent !== null && selected.agent !== agent)) return yield* Effect.die(new AgentMismatch())
  143. })
  144. export const requestReplacement = Effect.fn("SessionContextEpoch.requestReplacement")(function* (
  145. db: DatabaseService,
  146. sessionID: SessionSchema.ID,
  147. seq: number,
  148. ) {
  149. return yield* db
  150. .update(SessionContextEpochTable)
  151. .set({ replacement_seq: seq, revision: sql`${SessionContextEpochTable.revision} + 1` })
  152. .where(
  153. and(
  154. eq(SessionContextEpochTable.session_id, sessionID),
  155. lt(SessionContextEpochTable.baseline_seq, seq),
  156. or(isNull(SessionContextEpochTable.replacement_seq), lt(SessionContextEpochTable.replacement_seq, seq)),
  157. ),
  158. )
  159. .run()
  160. .pipe(Effect.orDie)
  161. })
  162. export const reset = Effect.fn("SessionContextEpoch.reset")(function* (
  163. db: DatabaseService,
  164. sessionID: SessionSchema.ID,
  165. ) {
  166. yield* db
  167. .delete(SessionContextEpochTable)
  168. .where(eq(SessionContextEpochTable.session_id, sessionID))
  169. .run()
  170. .pipe(Effect.orDie)
  171. })
  172. const insert = Effect.fnUntraced(function* (
  173. db: DatabaseService,
  174. sessionID: SessionSchema.ID,
  175. location: Location.Ref,
  176. agent: AgentV2.ID,
  177. generation: SystemContext.Generation,
  178. ) {
  179. return yield* db
  180. .transaction(
  181. () =>
  182. Effect.gen(function* () {
  183. const placed = yield* db
  184. .select({ agent: SessionTable.agent })
  185. .from(SessionTable)
  186. .where(
  187. and(
  188. eq(SessionTable.id, sessionID),
  189. eq(SessionTable.directory, location.directory),
  190. location.workspaceID === undefined
  191. ? isNull(SessionTable.workspace_id)
  192. : eq(SessionTable.workspace_id, location.workspaceID),
  193. ),
  194. )
  195. .get()
  196. .pipe(Effect.orDie)
  197. if (!placed) return yield* Effect.die(new LocationMismatch())
  198. if (placed.agent !== null && placed.agent !== agent) return yield* Effect.die(new AgentMismatch())
  199. const baselineSeq = yield* SessionInput.latestSeq(db, sessionID)
  200. yield* db
  201. .insert(SessionContextEpochTable)
  202. .values({
  203. session_id: sessionID,
  204. baseline: generation.baseline,
  205. agent,
  206. snapshot: generation.snapshot,
  207. baseline_seq: baselineSeq,
  208. revision: 0,
  209. })
  210. .onConflictDoNothing()
  211. .returning({ sessionID: SessionContextEpochTable.session_id })
  212. .get()
  213. .pipe(
  214. Effect.orDie,
  215. Effect.flatMap((inserted) => (inserted ? Effect.void : Effect.die(new RevisionMismatch()))),
  216. )
  217. return baselineSeq
  218. }),
  219. { behavior: "immediate" },
  220. )
  221. .pipe(Effect.orDie)
  222. })
  223. const replace = Effect.fnUntraced(function* (
  224. db: DatabaseService,
  225. sessionID: SessionSchema.ID,
  226. agent: AgentV2.ID,
  227. expectedRevision: number,
  228. baselineSeq: number,
  229. generation: SystemContext.Generation,
  230. ) {
  231. yield* db
  232. .transaction(
  233. () =>
  234. Effect.gen(function* () {
  235. yield* requireAgentSelection(db, sessionID, agent)
  236. const updated = yield* db
  237. .update(SessionContextEpochTable)
  238. .set({
  239. baseline: generation.baseline,
  240. agent,
  241. snapshot: generation.snapshot,
  242. baseline_seq: baselineSeq,
  243. replacement_seq: null,
  244. revision: expectedRevision + 1,
  245. })
  246. .where(
  247. and(
  248. eq(SessionContextEpochTable.session_id, sessionID),
  249. eq(SessionContextEpochTable.revision, expectedRevision),
  250. ),
  251. )
  252. .returning({ revision: SessionContextEpochTable.revision })
  253. .get()
  254. .pipe(Effect.orDie)
  255. if (!updated) return yield* Effect.die(new RevisionMismatch())
  256. }),
  257. { behavior: "immediate" },
  258. )
  259. .pipe(Effect.orDie)
  260. })
  261. const fence = Effect.fnUntraced(function* (
  262. db: DatabaseService,
  263. sessionID: SessionSchema.ID,
  264. agent: AgentV2.ID,
  265. expectedRevision: number,
  266. ) {
  267. const current = yield* db
  268. .select({ selected: SessionTable.agent, revision: SessionContextEpochTable.revision })
  269. .from(SessionContextEpochTable)
  270. .innerJoin(SessionTable, eq(SessionTable.id, SessionContextEpochTable.session_id))
  271. .where(eq(SessionContextEpochTable.session_id, sessionID))
  272. .get()
  273. .pipe(Effect.orDie)
  274. if (!current || (current.selected !== null && current.selected !== agent))
  275. return yield* Effect.die(new AgentMismatch())
  276. if (current.revision !== expectedRevision) return yield* Effect.die(new RevisionMismatch())
  277. })
  278. export const current = Effect.fn("SessionContextEpoch.current")(function* (
  279. db: DatabaseService,
  280. sessionID: SessionSchema.ID,
  281. agent: AgentV2.ID,
  282. revision: number,
  283. ) {
  284. const value = yield* db
  285. .select({
  286. agent: SessionContextEpochTable.agent,
  287. selected: SessionTable.agent,
  288. revision: SessionContextEpochTable.revision,
  289. })
  290. .from(SessionContextEpochTable)
  291. .innerJoin(SessionTable, eq(SessionTable.id, SessionContextEpochTable.session_id))
  292. .where(eq(SessionContextEpochTable.session_id, sessionID))
  293. .get()
  294. .pipe(Effect.orDie)
  295. return (
  296. value !== undefined &&
  297. value.agent === agent &&
  298. (value.selected === null || value.selected === agent) &&
  299. value.revision === revision
  300. )
  301. })
  302. const advance = Effect.fnUntraced(function* (
  303. db: DatabaseService,
  304. sessionID: SessionSchema.ID,
  305. expectedRevision: number,
  306. snapshot: SystemContext.Snapshot,
  307. ) {
  308. const updated = yield* db
  309. .update(SessionContextEpochTable)
  310. .set({ snapshot, revision: expectedRevision + 1 })
  311. .where(
  312. and(
  313. eq(SessionContextEpochTable.session_id, sessionID),
  314. eq(SessionContextEpochTable.revision, expectedRevision),
  315. isNull(SessionContextEpochTable.replacement_seq),
  316. ),
  317. )
  318. .returning({ revision: SessionContextEpochTable.revision })
  319. .get()
  320. .pipe(Effect.orDie)
  321. if (!updated) return yield* Effect.die(new RevisionMismatch())
  322. })