Skip to content
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

Segmentation Fault when using Bree workers with Prisma on Windows #15961

Closed
Richards0nd opened this issue Dec 23, 2024 · 1 comment
Closed

Segmentation Fault when using Bree workers with Prisma on Windows #15961

Richards0nd opened this issue Dec 23, 2024 · 1 comment
Labels
crash An issue that could cause a crash runtime windows An issue that is known to occur on Windows

Comments

@Richards0nd
Copy link

Richards0nd commented Dec 23, 2024

How can we reproduce the crash?

Bun Version: 1.1.42
System: Windows 11 24H2 26100.2605

Codes:

app.js (fastify):

import { env } from '@/shared/config/env'
import { errorHandler } from '@/shared/errors/errorHandler'
import fastifyCors from '@fastify/cors'
import fastifyJwt from '@fastify/jwt'
import fastifySwagger from '@fastify/swagger'
import fastifySwaggerUI from '@fastify/swagger-ui'
import { fastify } from 'fastify'
import {
	type ZodTypeProvider,
	jsonSchemaTransform,
	serializerCompiler,
	validatorCompiler
} from 'fastify-type-provider-zod'
import { initJobs } from '../jobs'
import { routes } from './routes'

const app = fastify().withTypeProvider<ZodTypeProvider>()

app.setSerializerCompiler(serializerCompiler)
app.setValidatorCompiler(validatorCompiler)
app.setErrorHandler(errorHandler)

app.register(fastifySwagger, {
	openapi: {
		info: {
			title: 'TITLE',
			description: 'DESCRIPTION',
			version: '1.0.0'
		},
		components: {
			securitySchemes: {
				bearerAuth: {
					type: 'http',
					scheme: 'bearer',
					bearerFormat: 'JWT'
				}
			}
		}
	},
	transform: jsonSchemaTransform
})

app.register(fastifySwaggerUI, { routePrefix: '/docs' })

app.register(fastifyJwt, { secret: env.JWT_SECRET })

app.register(fastifyCors)

app.register(routes)

app.listen({ host: env.APP_HOST, port: env.APP_PORT }, (err, address) => {
	if (err) {
		console.error(err)
		process.exit(1)
	}
	console.log(`Interal address ${address}`)
	console.log(`Server listening on http://${env.APP_HOST}:${env.APP_PORT}`)
})

initJobs()

jobs (bree):

import path from 'node:path'
import Bree from 'bree'

const jobPath = path.resolve(__dirname, '../../application/jobs/teste.ts')

const bree = new Bree({
	defaultExtension: 'ts',
	root: false,
	jobs: [
		{
			name: 'teste',
			path: jobPath,
			cron: '* * * * *',
			closeWorkerAfterMs: 10000,
			timeout: 20000
		}
	],
	outputWorkerMetadata: true
})

export function initJobs() {
	console.log('Iniciando')
	bree.start()

	bree.on('worker created', (name) => {
		console.log(`Worker created for job: ${name}`)
	})

	bree.on('worker error', (name, error) => {
		console.error(`Worker error for job: ${name}`, error.message)
	})

	bree.on('worker deleted', (name) => {
		console.log(`Worker deleted for job: ${name}`)
	})

	bree.on('worker failed', (name) => {
		console.error(`Worker failed for job: ${name}`)
	})
}

process.on('SIGINT', () => {
	console.log('Encerrando aplicação...')
	bree.stop().then(() => {
		console.log('Jobs parados.')
		process.exit(0)
	})
})

process.on('SIGTERM', () => {
	console.log('Recebido SIGTERM, encerrando aplicação...')
	bree.stop().then(() => {
		console.log('Jobs parados.')
		process.exit(0)
	})
})

Job test:

import { prisma } from '@/infrastructure/prisma/client'

async function processPendingChecklists() {
	const pendingChecklists = await prisma.checklists.findMany({
		where: {
			status: 'PENDING'
		},
		include: {
			ChecklistStages: {
				include: {
					Stage: true
				}
			},
			Appointments: true
		}
	})

	const now = new Date()

	for (const checklist of pendingChecklists) {
		for (const stage of checklist.ChecklistStages) {
			if (stage.status === 'PENDING' && stage.Stage.name === 'ESPELHAMENTO DE SINAL') {
				const latestAppointment = checklist.Appointments.reduce((latest, appointment) => {
					return appointment.date > latest.date ? appointment : latest
				}, checklist.Appointments[0])

				if (latestAppointment.date >= now) {
					const timeDiff =
						(now.getTime() - new Date(stage.createdAt).getTime()) / (1000 * 60)
					if (timeDiff > 60) {
						await prisma.negotiations.create({
							data: {
								checklistId: checklist.id,
								type: 'MIRRORING',
								description: 'Espelhamento de sinal pendente por mais de 60 minutos.',
								status: 'PENDING',
								createdAt: now
							}
						})
					}
				}
			}
		}
	}
}

await processPendingChecklists()

Before the test JOB it was like this at the end:

processPendingChecklists().catch((e) => {
	console.error(e)
})

However, I modified it so that it is an await

Relevant log output

PS C:\Users\Richardson Douglas\Documents\Verttice\vrtc_checklist_back> bun -v
1.1.42
PS C:\Users\Richardson Douglas\Documents\Verttice\vrtc_checklist_back> bun dev
$ bun --watch src/infrastructure/fastify/app.ts
Iniciando
Interal address http://127.0.0.1:3000
Server listening on http://0.0.0.0:3000
Worker created for job: teste
prisma:info Starting a postgresql pool with 21 connections.
Worker for job "teste" online {
  worker: {
    isMainThread: undefined,
    resourceLimits: undefined,
    threadId: 2,
  },
}
Worker for job "teste" exited with code 0 {
  worker: {
    isMainThread: undefined,
    resourceLimits: undefined,
    threadId: 2,
  },
}
Worker deleted for job: teste
============================================================
Bun Canary v1.1.42-canary.10 (774e30d3) Windows x64
Windows v.win10_fe
CPU: sse42 avx avx2
Args: "C:\Users\Richardson Douglas\.bun\bin\bun.exe" "--watch" "src/infrastructure/fastify/app.ts"
Features: dotenv(3) http_server jsc transpiler_cache(14) tsconfig(2) tsconfig_paths workers_spawned workers_terminated process_dlopen(2) 
Builtins: "bun:main" "node:assert" "node:async_hooks" "node:buffer" "node:child_process" "node:crypto" "node:dns" "node:events" "node:fs" "node:fs/promises" "node:http" "node:https" "node:os" "node:path" "node:stream" "node:string_decoder" "node:tty" "node:url" "node:util" "node:util/types" "node:zlib" "node:worker_threads" "node:diagnostics_channel" 
Elapsed: 20760ms | User: 625ms | Sys: 484ms
RSS: 0.50GB | Peak: 0.50GB | Commit: 0.64GB | Faults: 144248

panic(thread 10620): Segmentation fault at address 0x3B900000232
oh no: Bun has crashed. This indicates a bug in Bun, not your code.

To send a redacted crash report to Bun's team,
please file a GitHub issue using the link below:

 https://bun.report/1.1.42/wa2774e30d6Chw/6//B_0rw9jCwlq7rBy1u9rB+n1isB4u40sBg6gypB4nv8dggz5f2m+mmBA2y7BkjB

--- Bun is auto-restarting due to crash [time: 1734970205698] ---
Iniciando
EADDRINUSE: Failed to start server. Is port 3000 in use?
 syscall: "listen"

      at serve (node:http:541:41)

error: script "dev" exited with code 1

Stack Trace (bun.report)

Bun v1.1.42-canary (774e30d) on windows x86_64 [AutoCommand]

Segmentation fault at address 0xFFFFFFFFFFFFFFFF

Features: tsconfig_paths, workers_spawned, workers_terminated, process_dlopen, dotenv, http_server, jsc, transpiler_cache, tsconfig, tsconfig

Sentry Issue: BUN-854

@Richards0nd Richards0nd added the crash An issue that could cause a crash label Dec 23, 2024
@github-actions github-actions bot added runtime windows An issue that is known to occur on Windows labels Dec 23, 2024
@Jarred-Sumner
Copy link
Collaborator

Tracking this in #15964

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
crash An issue that could cause a crash runtime windows An issue that is known to occur on Windows
Projects
None yet
Development

No branches or pull requests

2 participants