fix(server): address vcs and log retention review

This commit is contained in:
Ben Davis committed 2026-06-26 13:35:33 -07:00
1 parent a9a23e489a
commit 40c5fc2121
5 files changed
+104 -20

No files matched your search

@@ -44,6 +44,13 @@ function parseLogLine(line: string) {
};
}
function threadLogPath(basePath: string, threadSegment: string) {
return NodePath.join(
NodePath.dirname(basePath),
`${NodePath.parse(basePath).name}-${threadSegment}.log`,
);
}
describe("EventNdjsonLogger", () => {
it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
const messages: Array<unknown> = [];
@@ -100,8 +107,8 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const threadOnePath = NodePath.join(tempDir, "thread-1.log");
const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
const threadOnePath = threadLogPath(basePath, "thread-1");
const threadTwoPath = threadLogPath(basePath, "thread-2");
assert.equal(NodeFS.existsSync(threadOnePath), true);
assert.equal(NodeFS.existsSync(threadTwoPath), true);
@@ -142,7 +149,7 @@ describe("EventNdjsonLogger", () => {
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
yield* logger.close();
const globalPath = NodePath.join(tempDir, "_global.log");
const globalPath = threadLogPath(basePath, "_global");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -185,7 +192,7 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const globalPath = NodePath.join(tempDir, "_global.log");
const globalPath = threadLogPath(basePath, "_global");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -221,7 +228,7 @@ describe("EventNdjsonLogger", () => {
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-shared.log"), "utf8")
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-shared"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
@@ -260,7 +267,7 @@ describe("EventNdjsonLogger", () => {
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(NodePath.join(tempDir, "thread-filtered.log"), "utf8")
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-filtered"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
@@ -308,7 +315,7 @@ describe("EventNdjsonLogger", () => {
}
yield* store.close();
const fileStem = "thread-rotate.log";
const fileStem = NodePath.basename(threadLogPath(basePath, "thread-rotate"));
const matchingFiles = NodeFS.readdirSync(tempDir)
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
.toSorted();
@@ -360,7 +367,7 @@ describe("EventNdjsonLogger", () => {
);
yield* store.close();
const filePath = NodePath.join(tempDir, "thread-oversized.log");
const filePath = threadLogPath(basePath, "thread-oversized");
assert.isAtMost(NodeFS.statSync(filePath).size, 256);
const line = parseLogLine(NodeFS.readFileSync(filePath, "utf8").trim());
const payload = decodeOmittedRecord(line.payload);
@@ -368,7 +375,7 @@ describe("EventNdjsonLogger", () => {
assert.equal(payload.eventType, "item.completed");
assert.isAbove(payload.originalBytes, 2_000);
const longTypeFilePath = NodePath.join(tempDir, "thread-oversized-type.log");
const longTypeFilePath = threadLogPath(basePath, "thread-oversized-type");
assert.isAtMost(NodeFS.statSync(longTypeFilePath).size, 256);
const longTypeLine = parseLogLine(NodeFS.readFileSync(longTypeFilePath, "utf8").trim());
const longTypePayload = decodeOmittedRecord(longTypeLine.payload);
@@ -383,20 +390,22 @@ describe("EventNdjsonLogger", () => {
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
const expiredPath = NodePath.join(tempDir, "expired.log");
const oldPath = NodePath.join(tempDir, "old.log");
const newPath = NodePath.join(tempDir, "new.log");
const expiredPath = threadLogPath(basePath, "expired");
const oldPath = threadLogPath(basePath, "old");
const newPath = threadLogPath(basePath, "new");
const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
try {
yield* TestClock.setTime(1_800_000_000_000);
const now = yield* Clock.currentTimeMillis;
for (const filePath of [expiredPath, oldPath, newPath, ignoredPath]) {
for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
NodeFS.writeFileSync(filePath, "x".repeat(400));
}
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
NodeFS.utimesSync(unrelatedLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
const store = yield* makeEventNdjsonLogStore(basePath, {
maxAgeMs: 10_000,
@@ -407,6 +416,7 @@ describe("EventNdjsonLogger", () => {
assert.equal(NodeFS.existsSync(expiredPath), false);
assert.equal(NodeFS.existsSync(oldPath), false);
assert.equal(NodeFS.existsSync(newPath), true);
assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
assert.equal(NodeFS.existsSync(ignoredPath), true);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
@@ -442,7 +452,7 @@ describe("EventNdjsonLogger", () => {
yield* store.close();
const totalBytes = NodeFS.readdirSync(tempDir, { withFileTypes: true })
.filter((entry) => entry.isFile() && /\.log(?:\.\d+)?$/u.test(entry.name))
.filter((entry) => entry.isFile() && /^events-.+\.log(?:\.\d+)?$/u.test(entry.name))
.reduce(
(total, entry) => total + NodeFS.statSync(NodePath.join(tempDir, entry.name)).size,
0,
@@ -36,7 +36,6 @@ const DEFAULT_MAX_RECORD_BYTES = MEBIBYTE;
const DEFAULT_MAX_CACHED_SINKS = 64;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
const PROVIDER_LOG_FILE_PATTERN = /\.log(?:\.\d+)?$/u;
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const transientCanonicalEventTypes = new Set([
@@ -244,6 +243,7 @@ function writeBatchedRecords(
function enforceRetention(input: {
readonly directory: string;
readonly filePattern: RegExp;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly now: number;
@@ -263,7 +263,7 @@ function enforceRetention(input: {
}
for (const entry of entries) {
if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue;
if (!entry.isFile() || !input.filePattern.test(entry.name)) continue;
const filePath = NodePath.join(input.directory, entry.name);
try {
const stat = NodeFS.statSync(filePath);
@@ -352,6 +352,8 @@ function resolveOptions(filePath: string, options: EventNdjsonLogStoreOptions) {
function drainPending(input: {
readonly directory: string;
readonly filePrefix: string;
readonly filePattern: RegExp;
readonly options: ResolvedOptions;
readonly state: StoreState;
readonly now: number;
@@ -373,7 +375,7 @@ function drainPending(input: {
let writtenBytes = 0;
for (const [threadSegment, records] of recordsBySegment) {
const filePath = NodePath.join(input.directory, `${threadSegment}.log`);
const filePath = NodePath.join(input.directory, `${input.filePrefix}-${threadSegment}.log`);
let sink = sinks.get(threadSegment);
try {
if (!sink) {
@@ -412,6 +414,7 @@ function drainPending(input: {
const retention = retentionDue
? enforceRetention({
directory: input.directory,
filePattern: input.filePattern,
maxTotalBytes: input.options.maxTotalBytes,
maxAgeMs: input.options.maxAgeMs,
now: input.now,
@@ -452,6 +455,9 @@ export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
const resolved = yield* resolveOptions(filePath, options);
const directory = NodePath.dirname(filePath);
const filePrefix =
toSafeThreadAttachmentSegment(NodePath.parse(filePath).name) ?? "provider-events";
const filePattern = new RegExp(`^${filePrefix}-.+\\.log(?:\\.\\d+)?$`, "u");
yield* Effect.try({
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
@@ -462,6 +468,7 @@ export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
const initialRetention = yield* Effect.sync(() =>
enforceRetention({
directory,
filePattern,
maxTotalBytes: resolved.maxTotalBytes,
maxAgeMs: resolved.maxAgeMs,
now: initializedAt,
@@ -499,6 +506,8 @@ export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
Effect.sync(() =>
drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state,
now,
@@ -569,6 +578,8 @@ export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
return Effect.sync(() => {
const [drainResult, drainedState] = drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state: nextState,
now,
+4 -3
View File
@@ -50,7 +50,7 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000;
const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000;
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.minutes(1);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
@@ -112,12 +112,13 @@ class StatusRemoteRefreshCacheKey {
return (
that instanceof StatusRemoteRefreshCacheKey &&
this.objectDir === that.objectDir &&
this.remoteName === that.remoteName
this.remoteName === that.remoteName &&
this.cwd === that.cwd
);
}
[Hash.symbol]() {
return Hash.string(`${this.objectDir}\0${this.remoteName}`);
return Hash.string(`${this.objectDir}\0${this.remoteName}\0${this.cwd}`);
}
}
@@ -865,6 +865,65 @@ describe("VcsStatusBroadcaster", () => {
}),
);
it.effect("does not continue remote status work after an upstream refresh is interrupted", () => {
const state = {
remoteStatusCalls: 0,
remoteInvalidationCalls: 0,
};
let refreshStartedDeferred: Deferred.Deferred<void> | null = null;
let refreshInterruptedDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () =>
Effect.gen(function* () {
if (refreshStartedDeferred) {
yield* Deferred.succeed(refreshStartedDeferred, undefined);
}
return yield* Effect.never;
}).pipe(
Effect.onInterrupt(() =>
refreshInterruptedDeferred
? Deferred.succeed(refreshInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return baseRemoteStatus;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
return Effect.gen(function* () {
refreshStartedDeferred = yield* Deferred.make<void>();
refreshInterruptedDeferred = yield* Deferred.make<void>();
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
yield* broadcaster
.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
)
.pipe(Stream.runDrain, Effect.forkIn(scope));
yield* Deferred.await(refreshStartedDeferred);
yield* Scope.close(scope, Exit.void);
yield* Deferred.await(refreshInterruptedDeferred);
assert.equal(state.remoteInvalidationCalls, 0);
assert.equal(state.remoteStatusCalls, 0);
}).pipe(Effect.provide(testLayer));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -375,6 +375,9 @@ export const make = Effect.gen(function* () {
options?.refreshUpstream === false
? Exit.void
: yield* workflow.refreshStatusUpstream(cwd).pipe(Effect.exit);
if (Exit.isFailure(refreshExit) && Cause.hasInterrupts(refreshExit.cause)) {
return yield* Effect.failCause(refreshExit.cause);
}
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}