{"record":{"id":"26f4e5f1fee362e1","repo":"deepinsight/insightface","slug":"herr-invalid-context-handle","errorCode":"HERR_INVALID_CONTEXT_HANDLE","errorMessage":"{operation}: Session not initialized","messagePattern":"(.+?): Session not initialized","errorType":"exception","errorClass":"ResourceError","httpStatus":null,"severity":"error","filePath":"cpp-package/inspireface/python/inspireface/modules/exception.py","lineNumber":219,"sourceCode":"    if not isinstance(data, np.ndarray):\n        raise InvalidInputError(\n            f\"{operation}: Feature data must be a numpy array\",\n            errcode.HERR_INVALID_FACE_FEATURE,\n            input_type=type(data).__name__\n        )\n    \n    if data.dtype != np.float32:\n        raise InvalidInputError(\n            f\"{operation}: Feature data must be in float32 format\",\n            errcode.HERR_INVALID_FACE_FEATURE,\n            actual_dtype=str(data.dtype)\n        )\n\n\ndef validate_session_initialized(session, operation: str = \"Session operation\"):\n    \"\"\"Validate if session is initialized\"\"\"\n    if session is None or session._sess is None:\n        raise ResourceError(\n            f\"{operation}: Session not initialized\",\n            errcode.HERR_INVALID_CONTEXT_HANDLE\n        )\n\n\n# === Exception handling decorators for special scenarios ===\n\ndef handle_c_api_errors(operation_name: str):\n    \"\"\"Decorator for wrapping C API calls\"\"\"\n    def decorator(func):\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except Exception as e:\n                if not isinstance(e, InspireFaceError):\n                    # Wrap non-InspireFace exceptions as ProcessingError\n                    raise ProcessingError(\n                        f\"{operation_name}: {str(e)}\",","sourceCodeStart":201,"sourceCodeEnd":237,"githubUrl":"https://github.com/deepinsight/insightface/blob/7fadd420c2351d0ffa8cac403421c1a3ed733365/cpp-package/inspireface/python/inspireface/modules/exception.py#L201-L237","documentation":"validate_session_initialized() raises ResourceError (HERR_INVALID_CONTEXT_HANDLE) when session is None or its internal session._sess handle is None. It guards every per-frame API (face_detection, landmarks, tracking options, thresholds) so you never pass a dead context into the C layer.","triggerScenarios":"Calling face_detection / get_face_five_key_points / get_face_dense_landmark / set_detection_confidence_threshold etc. on a session whose construction failed partway, after session.release()/close, or on a bare/None session object.","commonSituations":"Continuing to use a session after cleanup in a server loop; swallowing a construction exception and proceeding; reusing a session forked across processes where the handle is invalid; double-close patterns.","solutions":["Recreate the session: param = SessionCustomParameter(); session = InspireFaceSession(param, ...)","Ensure the original InspireFaceSession(...) constructor did not throw (launch/resource errors surface there)","Scope usage: create the session once and stop using it after release(); guard with if session and session._sess is not None"],"exampleFix":"# before\nsession.release()\n# ... later ...\nsession.face_detection(img)  # ResourceError\n# after\nsession.release()\nsession = InspireFaceSession(SessionCustomParameter(), detect_mode=0, max_detect_num=10)\nsession.face_detection(img)","handlingStrategy":"validation","validationCode":"assert session is not None and getattr(session, '_sess', None) is not None, 'session dead'","typeGuard":"def session_alive(sess) -> bool:\n    return sess is not None and getattr(sess, '_sess', None) is not None","tryCatchPattern":"from inspireface.modules.exception import ResourceError\ntry:\n    faces = session.face_detection(img)\nexcept ResourceError:\n    session = InspireFaceSession(SessionCustomParameter(), 0, 10)  # recreate\n    faces = session.face_detection(img)","preventionTips":["Create sessions in try/finally and set them to None after release()","In servers, hold one session per process and health-check _sess before requests"],"tags":["session-lifecycle","resource","context-handle","inspireface"],"backgroundTag":"uninitialized-session-handle","analyzedSha":"7fadd420c2351d0ffa8cac403421c1a3ed733365","analyzedAt":"2026-08-28T15:44:01.850Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}