-
Notifications
You must be signed in to change notification settings - Fork 28
fix(code): coalesce writeLocalLogs per taskRunId to stop main-thread storm #2255
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
k11kirky
wants to merge
4
commits into
main
Choose a base branch
from
posthog-code/debounce-write-local-logs
base: main
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
4 commits
Select commit
Hold shift + click to select a range
b600503
fix(code): coalesce writeLocalLogs per taskRunId to stop main-thread …
k11kirky cdc3304
refactor(code): trim LocalLogsService docblock and dedup mkdir + same…
k11kirky 307c262
chore(code): dedupe duplicate INBOX_VIEWED analytics declarations
k11kirky d7b92a8
test(code): parameterize readLocalLogs null-return cases
k11kirky 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,234 @@ | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| const { mockMkdir, mockWriteFile, mockReadFile } = vi.hoisted(() => ({ | ||
| mockMkdir: vi.fn(), | ||
| mockWriteFile: vi.fn(), | ||
| mockReadFile: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock("node:fs", () => ({ | ||
| default: { | ||
| promises: { | ||
| mkdir: mockMkdir, | ||
| writeFile: mockWriteFile, | ||
| readFile: mockReadFile, | ||
| }, | ||
| }, | ||
| })); | ||
|
|
||
| vi.mock("../../utils/logger.js", () => ({ | ||
| logger: { | ||
| scope: () => ({ | ||
| info: vi.fn(), | ||
| error: vi.fn(), | ||
| warn: vi.fn(), | ||
| debug: vi.fn(), | ||
| }), | ||
| }, | ||
| })); | ||
|
|
||
| import { LocalLogsService } from "./service"; | ||
|
|
||
| const RUN_ID = "run-abc"; | ||
| const expectedPath = path.join( | ||
| os.homedir(), | ||
| ".posthog-code", | ||
| "sessions", | ||
| RUN_ID, | ||
| "logs.ndjson", | ||
| ); | ||
|
|
||
| function deferred<T = void>(): { | ||
| promise: Promise<T>; | ||
| resolve: (value: T) => void; | ||
| reject: (err: unknown) => void; | ||
| } { | ||
| let resolve!: (value: T) => void; | ||
| let reject!: (err: unknown) => void; | ||
| const promise = new Promise<T>((res, rej) => { | ||
| resolve = res; | ||
| reject = rej; | ||
| }); | ||
| return { promise, resolve, reject }; | ||
| } | ||
|
|
||
| async function flushMicrotasks(): Promise<void> { | ||
| for (let i = 0; i < 5; i++) await Promise.resolve(); | ||
| } | ||
|
|
||
| describe("LocalLogsService", () => { | ||
| beforeEach(() => { | ||
| mockMkdir.mockReset().mockResolvedValue(undefined); | ||
| mockWriteFile.mockReset().mockResolvedValue(undefined); | ||
| mockReadFile.mockReset(); | ||
| }); | ||
|
|
||
| describe("readLocalLogs", () => { | ||
| it("returns file contents", async () => { | ||
| mockReadFile.mockResolvedValue("hello"); | ||
| const service = new LocalLogsService(); | ||
| await expect(service.readLocalLogs(RUN_ID)).resolves.toBe("hello"); | ||
| expect(mockReadFile).toHaveBeenCalledWith(expectedPath, "utf-8"); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["file is missing", Object.assign(new Error("nope"), { code: "ENOENT" })], | ||
| ["other read errors", new Error("boom")], | ||
| ])("returns null when %s", async (_label, err) => { | ||
| mockReadFile.mockRejectedValue(err); | ||
| const service = new LocalLogsService(); | ||
| await expect(service.readLocalLogs(RUN_ID)).resolves.toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("writeLocalLogs", () => { | ||
| it("writes content to the run's NDJSON path", async () => { | ||
| const service = new LocalLogsService(); | ||
| await service.writeLocalLogs(RUN_ID, "line1\n"); | ||
| expect(mockMkdir).toHaveBeenCalledWith(path.dirname(expectedPath), { | ||
| recursive: true, | ||
| }); | ||
| expect(mockWriteFile).toHaveBeenCalledWith( | ||
| expectedPath, | ||
| "line1\n", | ||
| "utf-8", | ||
| ); | ||
| }); | ||
|
|
||
| it("collapses many concurrent writes to one in-flight + one queued", async () => { | ||
| const firstWrite = deferred(); | ||
| mockWriteFile.mockImplementationOnce(() => firstWrite.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
|
|
||
| const a = service.writeLocalLogs(RUN_ID, "A"); | ||
| const b = service.writeLocalLogs(RUN_ID, "B"); | ||
| const c = service.writeLocalLogs(RUN_ID, "C"); | ||
| const d = service.writeLocalLogs(RUN_ID, "D"); | ||
|
|
||
| await flushMicrotasks(); | ||
| expect(mockWriteFile).toHaveBeenCalledTimes(1); | ||
| expect(mockWriteFile).toHaveBeenCalledWith(expectedPath, "A", "utf-8"); | ||
|
|
||
| firstWrite.resolve(); | ||
| await Promise.all([a, b, c, d]); | ||
|
|
||
| expect(mockWriteFile).toHaveBeenCalledTimes(2); | ||
| expect(mockWriteFile).toHaveBeenNthCalledWith( | ||
| 2, | ||
| expectedPath, | ||
| "D", | ||
| "utf-8", | ||
| ); | ||
| }); | ||
|
|
||
| it("all coalesced callers see resolution when drain completes", async () => { | ||
| const firstWrite = deferred(); | ||
| mockWriteFile.mockImplementationOnce(() => firstWrite.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
| const a = service.writeLocalLogs(RUN_ID, "A"); | ||
| const b = service.writeLocalLogs(RUN_ID, "B"); | ||
|
|
||
| let aResolved = false; | ||
| let bResolved = false; | ||
| void a.then(() => { | ||
| aResolved = true; | ||
| }); | ||
| void b.then(() => { | ||
| bResolved = true; | ||
| }); | ||
|
|
||
| await Promise.resolve(); | ||
| expect(aResolved).toBe(false); | ||
| expect(bResolved).toBe(false); | ||
|
|
||
| firstWrite.resolve(); | ||
| await Promise.all([a, b]); | ||
| expect(aResolved).toBe(true); | ||
| expect(bResolved).toBe(true); | ||
| }); | ||
|
|
||
| it("keeps writes for different taskRunIds independent", async () => { | ||
| const writeA = deferred(); | ||
| const writeB = deferred(); | ||
| mockWriteFile | ||
| .mockImplementationOnce(() => writeA.promise) | ||
| .mockImplementationOnce(() => writeB.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
| const a = service.writeLocalLogs("run-a", "AAA"); | ||
| const b = service.writeLocalLogs("run-b", "BBB"); | ||
|
|
||
| await flushMicrotasks(); | ||
| expect(mockWriteFile).toHaveBeenCalledTimes(2); | ||
| writeA.resolve(); | ||
| writeB.resolve(); | ||
| await Promise.all([a, b]); | ||
| }); | ||
|
|
||
| it("starts fresh after the queue drains", async () => { | ||
| const service = new LocalLogsService(); | ||
| await service.writeLocalLogs(RUN_ID, "first"); | ||
| await service.writeLocalLogs(RUN_ID, "second"); | ||
| expect(mockWriteFile).toHaveBeenCalledTimes(2); | ||
| expect(mockWriteFile).toHaveBeenNthCalledWith( | ||
| 2, | ||
| expectedPath, | ||
| "second", | ||
| "utf-8", | ||
| ); | ||
| }); | ||
|
|
||
| it("continues draining queued content even if a write rejects", async () => { | ||
| const firstWrite = deferred(); | ||
| mockWriteFile.mockImplementationOnce(() => firstWrite.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
| const a = service.writeLocalLogs(RUN_ID, "A"); | ||
| const b = service.writeLocalLogs(RUN_ID, "B"); | ||
|
|
||
| firstWrite.reject(new Error("disk full")); | ||
| await Promise.all([a, b]); | ||
|
|
||
| expect(mockWriteFile).toHaveBeenCalledTimes(2); | ||
| expect(mockWriteFile).toHaveBeenNthCalledWith( | ||
| 2, | ||
| expectedPath, | ||
| "B", | ||
| "utf-8", | ||
| ); | ||
| }); | ||
|
|
||
| it("skips writeFile when coalesced content matches the last write", async () => { | ||
| const firstWrite = deferred(); | ||
| mockWriteFile.mockImplementationOnce(() => firstWrite.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
| const a = service.writeLocalLogs(RUN_ID, "SAME"); | ||
| const b = service.writeLocalLogs(RUN_ID, "SAME"); | ||
|
|
||
| firstWrite.resolve(); | ||
| await Promise.all([a, b]); | ||
|
|
||
| expect(mockWriteFile).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("only mkdirs once per drain", async () => { | ||
| const firstWrite = deferred(); | ||
| mockWriteFile.mockImplementationOnce(() => firstWrite.promise); | ||
|
|
||
| const service = new LocalLogsService(); | ||
| const a = service.writeLocalLogs(RUN_ID, "A"); | ||
| const b = service.writeLocalLogs(RUN_ID, "B"); | ||
|
|
||
| firstWrite.resolve(); | ||
| await Promise.all([a, b]); | ||
|
|
||
| expect(mockWriteFile).toHaveBeenCalledTimes(2); | ||
| expect(mockMkdir).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
| }); | ||
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,108 @@ | ||
| import fs from "node:fs"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
|
|
||
| import { injectable } from "inversify"; | ||
| import { DATA_DIR } from "../../../shared/constants"; | ||
| import { logger } from "../../utils/logger"; | ||
|
|
||
| const log = logger.scope("local-logs"); | ||
|
|
||
| interface WriteState { | ||
| pending: string | undefined; | ||
| lastWritten: string | undefined; | ||
| dirReady: boolean; | ||
| } | ||
|
|
||
| /** | ||
| * Single-flight per `taskRunId` with latest-wins coalescing. Prevents the | ||
| * gap-reconcile loop from spawning parallel writeFile of the same NDJSON. | ||
| */ | ||
| @injectable() | ||
| export class LocalLogsService { | ||
| private writes = new Map< | ||
| string, | ||
| { state: WriteState; inFlight: Promise<void> } | ||
| >(); | ||
|
|
||
| async readLocalLogs(taskRunId: string): Promise<string | null> { | ||
| const logPath = this.getLocalLogPath(taskRunId); | ||
| try { | ||
| return await fs.promises.readFile(logPath, "utf-8"); | ||
| } catch (error) { | ||
| if ((error as NodeJS.ErrnoException).code === "ENOENT") { | ||
| return null; | ||
| } | ||
| log.warn("Failed to read local logs:", error); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| writeLocalLogs(taskRunId: string, content: string): Promise<void> { | ||
| const existing = this.writes.get(taskRunId); | ||
| if (existing) { | ||
| existing.state.pending = content; | ||
| return existing.inFlight; | ||
| } | ||
|
|
||
| const state: WriteState = { | ||
| pending: undefined, | ||
| lastWritten: undefined, | ||
| dirReady: false, | ||
| }; | ||
| const inFlight = this.drain(taskRunId, content, state); | ||
| this.writes.set(taskRunId, { state, inFlight }); | ||
| return inFlight; | ||
| } | ||
|
|
||
| private async drain( | ||
| taskRunId: string, | ||
| initialContent: string, | ||
| state: WriteState, | ||
| ): Promise<void> { | ||
| try { | ||
| let next: string | undefined = initialContent; | ||
| while (next !== undefined) { | ||
| const current = next; | ||
| next = undefined; | ||
| if (current !== state.lastWritten) { | ||
| await this.doWrite(taskRunId, current, state); | ||
| state.lastWritten = current; | ||
| } | ||
| if (state.pending !== undefined) { | ||
| next = state.pending; | ||
| state.pending = undefined; | ||
| } | ||
| } | ||
| } finally { | ||
| this.writes.delete(taskRunId); | ||
| } | ||
| } | ||
|
|
||
| private async doWrite( | ||
| taskRunId: string, | ||
| content: string, | ||
| state: WriteState, | ||
| ): Promise<void> { | ||
| const logPath = this.getLocalLogPath(taskRunId); | ||
| try { | ||
| if (!state.dirReady) { | ||
| await fs.promises.mkdir(path.dirname(logPath), { recursive: true }); | ||
| state.dirReady = true; | ||
| } | ||
| await fs.promises.writeFile(logPath, content, "utf-8"); | ||
| } catch (error) { | ||
| log.warn("Failed to write local logs:", error); | ||
| } | ||
| } | ||
|
|
||
| private getLocalLogPath(taskRunId: string): string { | ||
| return path.join( | ||
| os.homedir(), | ||
| DATA_DIR, | ||
| "sessions", | ||
| taskRunId, | ||
| "logs.ndjson", | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The two
readLocalLogstests —"returns null when the file is missing"and"returns null on other read errors"— differ only in the error object injected. Per the team style, these should be collapsed into a singleit.each.Context Used: Do not attempt to comment on incorrect alphabetica... (source)
Prompt To Fix With AI
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!