{"record":{"id":"856e63110b1d3f86","repo":"t8y2/dbx","slug":"agent-session-already-exists-sessionid","errorCode":null,"errorMessage":"Agent session already exists: {sessionId}","messagePattern":"Agent session already exists: (.+?)","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java","lineNumber":194,"sourceCode":"                new IllegalStateException(\"Agent session limit reached: \" + MAX_SESSIONS)\n            );\n        }\n        Session session;\n        if (sessionHandlerFactory != null) {\n            session = new Session(sessionHandlerFactory.get());\n        } else {\n            DatabaseAgent agent = agentFactory.get();\n            if (poolRegistry.isEnabled()\n                && agent instanceof AbstractJdbcAgent jdbcAgent\n                && jdbcAgent.supportsConnectionPooling()) {\n                jdbcAgent.attachConnectionPoolRegistry(poolRegistry);\n                ensureMaintenanceStarted();\n            }\n            session = new Session(new JsonRpcServer(agent));\n        }\n        Session existing = sessions.putIfAbsent(sessionId, session);\n        if (existing != null) {\n            throw new IllegalStateException(\"Agent session already exists: \" + sessionId);\n        }\n        try {\n            return session.connect(params);\n        } catch (Exception error) {\n            sessions.remove(sessionId, session);\n            session.quarantineAndClose(cleanup);\n            throw error;\n        }\n    }\n\n    private Object closeSession(String sessionId) {\n        Session session = sessions.remove(sessionId);\n        if (session != null) {\n            boolean replaceRuntime = session.quarantineAndClose(cleanup);\n            if (replaceRuntime) {\n                throw AgentRpcError.resource(\n                    \"close\",\n                    new IllegalStateException(\"JDBC quarantine operation limit reached\")","sourceCodeStart":176,"sourceCodeEnd":212,"githubUrl":"https://github.com/t8y2/dbx/blob/c0390bff16418b651f4728520d99adf8ce48829a/agents/common/src/main/java/com/dbx/agent/MultiSessionJsonRpcServer.java#L176-L212","documentation":"MultiSessionJsonRpcServer.openSession throws IllegalStateException when sessions.putIfAbsent finds an existing session under the same agentSessionId. Session IDs are caller-supplied, so this enforces uniqueness: one live agent session per ID.","triggerScenarios":"Calling openSession twice with the same agentSessionId without closing the first; a concurrent client racing to open the same ID; reusing an ID from a previous run whose session was not closed.","commonSituations":"Client retry after a timeout where the first open actually succeeded; fixed/default session IDs in client config; scripts re-run without closing previous sessions.","solutions":["Generate a unique agentSessionId (UUID) per session, or reuse the existing session via the request path instead of opening again","Close the existing session with the same ID before reopening","On receiving this error, treat the session as already connected and proceed with handleRequest using that ID","Serialize session-open logic client-side to avoid duplicate concurrent opens"],"exampleFix":"// before\nserver.openSession(\"main\", connectParams);\n// after\nString id = UUID.randomUUID().toString();\nserver.openSession(id, connectParams); // unique per run","handlingStrategy":"validation","validationCode":"// before opening, check whether the id already exists by attempting a harmless request\nboolean exists = true;\ntry { server.handleRequest(id, pingRequest); } catch (IllegalStateException e) { exists = false; }\nif (!exists) server.openSession(id, connectParams);","typeGuard":null,"tryCatchPattern":"try {\n    server.openSession(sessionId, connectParams);\n} catch (IllegalStateException e) {\n    // already open: reuse it\n}","preventionTips":["Generate session IDs with UUID.randomUUID()","Close sessions in a finally block or on client shutdown","Avoid fixed default session IDs shared across runs/clients","Handle open-retries idempotently: treat 'already exists' as success"],"tags":["session-management","concurrency","illegal-state","jsonrpc"],"backgroundTag":"session-already-exists","analyzedSha":"c0390bff16418b651f4728520d99adf8ce48829a","analyzedAt":"2026-09-05T23:05:10.900Z","contentChangedAt":"2026-09-05T23:05:10.900Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}