[codex] Prevent background Git fetches from leaking temp packs #3537
Closedjuliusmarmingewants to merge 7 commits into
main fromcodex/fix-git-fetch-temp-pack-leaksopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -923,0 +1007,21 @@1007+ if (yield* hasActiveFetchLock(gitCommonDir)) {1008+ yield* Effect.logWarning(1009+ "Skipped temporary Git pack cleanup while a fetch lock is active",1010+ {1011+ temporaryPackCount: newFiles.length,1012+ },1013+ );1014+ return;1015+ }1016+1017+ const packDir = path.join(gitCommonDir, "objects", "pack");1018+ const removalResults = yield* Effect.forEach(1019+ newFiles,1020+ (entry) =>1021+ fileSystem.remove(path.join(packDir, entry), { force: true }).pipe(1022+ Effect.as(true),1023+ Effect.catchTags({1024+ PlatformError: () => Effect.succeed(false),1025+ }),1026+ ),1027+ { concurrency: 1 },
- @@ -0,0 +221,21 @@221+222+ const shouldRunScopeWork: BackgroundPolicyShape["shouldRunScopeWork"] = (scope) =>223+ Effect.gen(function* () {224+ const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);225+ if (isHostConstrained(current.hostPower, settings)) {226+ return false;227+ }228+ return current.leases.some((lease) =>229+ leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),230+ );231+ });232+233+ const shouldRunOpportunisticWork = Effect.map(234+ snapshot,235+ (current) => current.shouldRunOpportunisticWork,236+ );237+238+ yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(239+ Effect.forkScoped,240+ );241+@@ -0,0 +436,21 @@436+ const ioReadDelta = previous437+ ? delta({438+ current: process.ioReadBytes,439+ previous: previous.process.ioReadBytes,440+ elapsedMs,441+ })442+ : 0;443+ const ioWriteDelta = previous444+ ? delta({445+ current: process.ioWriteBytes,446+ previous: previous.process.ioWriteBytes,447+ elapsedMs,448+ })449+ : 0;450+ const electronMetric = matchElectronMetric(process, metricsByPid);451+ const category: ResourceTelemetryProcessCategory =452+ process.pid === input.serverPid453+ ? "server"454+ : Option.contains(input.sidecarPid, process.pid)455+ ? "resource-monitor"456+ : explicitElectronRootPids.has(process.pid)@@ -0,0 +214,21 @@214+ Queue.take(sampleTriggers),215+ Effect.sleep(sampleInterval(currentPower, demand)),216+ );217+ yield* sampleOnce;218+ }219+ }).pipe(Effect.forkScoped);220+221+ const handleControl: DesktopTelemetryPublisherShape["handleControl"] = (message) => {222+ switch (message.type) {223+ case "setDiagnosticsDemand":224+ return Ref.getAndSet(diagnosticsDemand, message.enabled).pipe(225+ Effect.flatMap((previous) =>226+ previous === message.enabled227+ ? Effect.void228+ : Queue.offer(sampleTriggers, undefined).pipe(Effect.asVoid),229+ ),230+ );231+ }232+ };233+234+ const snapshots = Stream.concat(@@ -113,0 +203,21 @@203+ ? "advanced"204+ : settings.backgroundActivity.profile;205+}206+207+function resetBackgroundActivitySettings() {208+ return {209+ backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,210+ };211+}212+213+function backgroundActivityProfileSettings(profile: BackgroundActivityProfile) {214+ return {215+ backgroundActivity: {216+ schemaVersion: 1 as const,217+ profile,218+ overrides: {},219+ },220+ };221+}222+223+function backgroundActivityOverrideSettings(@@ -0,0 +632,21 @@632+ Effect.catchCause((cause) =>633+ Cause.hasInterruptsOnly(cause)634+ ? Effect.void635+ : Ref.update(state, (current) => ({636+ ...current,637+ status: "unavailable" as const,638+ hello: Option.none(),639+ lastError: Option.some(Cause.pretty(cause)),640+ })).pipe(641+ Effect.andThen(publishHealth),642+ Effect.andThen(643+ Effect.logWarning("Resource monitor supervisor failed", {644+ cause: Cause.pretty(cause),645+ }),646+ ),647+ ),648+ ),649+ Effect.forkScoped,650+ );651+652+ const applyCollectionControl = Effect.fn(@@ -0,0 +376,21 @@376+ Option.match(input.desktopSnapshot, {377+ onNone: () => input.fallbackSampledAtMs,378+ onSome: (snapshot) => snapshot.sampledAtUnixMs,379+ }),380+ onSome: (snapshot) => snapshot.sampledAtUnixMs,381+ });382+ const nativeByPid = new Map(nativeProcesses.map((process) => [process.pid, process]));383+ const metricsByPid = new Map<number, DesktopElectronProcessMetric>();384+ for (const metric of electronMetrics) {385+ const nativeProcess = nativeByPid.get(metric.pid);386+ if (!nativeProcess) {387+ nativeByPid.set(metric.pid, syntheticNativeSample(metric, sampledAtMs));388+ metricsByPid.set(metric.pid, metric);389+ continue;390+ }391+ if (392+ Math.abs(metric.creationTimeMs - nativeProcess.startTimeMs) <= ELECTRON_IDENTITY_TOLERANCE_MS393+ ) {394+ metricsByPid.set(metric.pid, metric);395+ }396+ }@@ -366,0 +420,21 @@420+ Option.some({421+ runId,422+ startDetails: sanitizeLogValue(details),423+ chunks: [],424+ byteLength: 0,425+ }),426+ );427+ }),428+ writeOutputChunk: Effect.fnUntraced(function* (streamName, chunk) {429+ if (environment.isDevelopment) {430+ yield* writeDevelopmentConsoleOutput(streamName, chunk);431+ }432+ yield* Ref.update(433+ sessionRef,434+ Option.map((session) => appendBoundedOutputChunk(session, streamName, chunk)),435+ );436+ }),437+ persistFailure: Effect.fn("desktop.observability.backendOutput.persistFailure")(function* ({438+ details,439+ }) {440+ const session = yield* Ref.modify(sessionRef, (current) => [@@ -0,0 +336,21 @@336+ status: "stopped",337+ lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),338+ }),339+ ),340+ ),341+ Effect.catch((error) =>342+ updateHealth(343+ (current): DesktopTelemetryReceiverHealth => ({344+ ...current,345+ status: "degraded",346+ lastError: Option.some(error.message),347+ }),348+ ),349+ ),350+ Effect.forkScoped,351+ );352+353+ yield* Effect.forever(354+ Effect.sleep(STALE_CHECK_INTERVAL).pipe(355+ Effect.andThen(356+ Effect.gen(function* () {@@ -0,0 +349,21 @@349+ switch (event.type) {350+ case "hello":351+ return Ref.update(state, (current) => ({352+ ...current,353+ status: "starting" as const,354+ hello: Option.some(event),355+ lastError: Option.none(),356+ })).pipe(357+ Effect.andThen(publishHealth),358+ Effect.andThen(Deferred.succeed(helloDeferred, event)),359+ Effect.asVoid,360+ );361+ case "snapshot":362+ return Effect.gen(function* () {363+ const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);364+ yield* Ref.update(state, (current) => ({365+ ...current,366+ status: "healthy" as const,367+ lastSampleAt: Option.some(sampledAt),368+ lastError: Option.none(),369+ }));@@ -101,9 +214,13 @@214+}): RetentionResult {215+ const failures: Array<FileOperationFailure> = [];216+ const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];217+218+ let entries: ReadonlyArray<NodeFS.Dirent>;219+ try {220+ entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });221+ } catch (cause) {222+ return { failures: [{ filePath: input.directory, cause }] };223+ }101224102-const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {103- readonly filePath: string;104- readonly maxBytes: number;105- readonly maxFiles: number;106- readonly batchWindowMs: number;107- readonly streamLabel: string;108-}): Effect.fn.Return<ThreadWriter | undefined> {109- const sinkResult = yield* Effect.sync(() => {225+ for (const entry of entries) {226+ if (!entry.isFile() || !PROVIDER_LOG_FILE_PATTERN.test(entry.name)) continue;@@ -0,0 +132,21 @@132+ samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),133+ maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),134+ ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),135+ ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),136+ maxProcessCount:137+ samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),138+ });139+ }140+ return buckets;141+}142+143+export function buildResourceTelemetryHistory(144+ input: BuildResourceTelemetryHistoryInput,145+): ResourceTelemetryHistory {146+ const readAtMs = DateTime.toEpochMillis(input.readAt);147+ const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);148+ const windowStartMs = readAtMs - windowMs;149+ const snapshots = input.snapshots150+ .filter((snapshot) => snapshot.sampledAtUnixMs >= windowStartMs)151+ .toSorted((left, right) => left.sampledAtUnixMs - right.sampledAtUnixMs);152+ const electronRootPids = Option.match(input.desktopSnapshot, {@@ -0,0 +25,21 @@25+26+export interface BackgroundPolicyShape {27+ readonly reportClientActivity: (28+ sessionId: AuthSessionId,29+ rpcClientId: RpcClientId,30+ input: ClientActivityReportInput,31+ ) => Effect.Effect<void>;32+ readonly removeRpcClient: (rpcClientId: RpcClientId) => Effect.Effect<void>;33+ readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;34+ readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;35+ readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;36+ readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;37+ readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;38+ readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;39+}40+41+export class BackgroundPolicy extends Context.Service<BackgroundPolicy, BackgroundPolicyShape>()(42+ "t3/background/BackgroundPolicy",43+) {}44+45+const DEFAULT_LEASE_TTL_MS = 45_000;@@ -0,0 +129,21 @@129+ endedAt: DateTime.makeUnsafe(endedAtMs),130+ avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,131+ maxCpuPercent:132+ samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),133+ maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),134+ ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),135+ ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),136+ maxProcessCount:137+ samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),138+ });139+ }140+ return buckets;141+}142+143+export function buildResourceTelemetryHistory(144+ input: BuildResourceTelemetryHistoryInput,145+): ResourceTelemetryHistory {146+ const readAtMs = DateTime.toEpochMillis(input.readAt);147+ const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);148+ const windowStartMs = readAtMs - windowMs;149+ const snapshots = input.snapshots@@ -156,4 +354,18 @@156- }),157- }).pipe(Effect.provideService(Scope.Scope, scope));354+ }158355159- const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });356+ try {357+ writeBatchedMessages(sink, records, input.options.maxBytes);358+ for (const record of records) {359+ const current = attributionByStream.get(record.stream) ?? {360+ count: 0,361+ logicalWriteBytes: 0,362+ };363+ attributionByStream.set(record.stream, {364+ count: current.count + 1,365+ logicalWriteBytes: current.logicalWriteBytes + record.bytes,366+ });367+ }368+ } catch (cause) {369+ failedSegments.add(threadSegment);370+ failures.push({ filePath, cause });371+ }
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
464bbb3b-a772-4a68-9e19-6cc604e2b870You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.