deepinsight/insightface · error · ResourceError

HERR_INVALID_CONTEXT_HANDLE

HERR_INVALID_CONTEXT_HANDLE

Error message

{operation}: Session not initialized

What it means

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.

Source

Thrown at cpp-package/inspireface/python/inspireface/modules/exception.py:219

    if not isinstance(data, np.ndarray):
        raise InvalidInputError(
            f"{operation}: Feature data must be a numpy array",
            errcode.HERR_INVALID_FACE_FEATURE,
            input_type=type(data).__name__
        )
    
    if data.dtype != np.float32:
        raise InvalidInputError(
            f"{operation}: Feature data must be in float32 format",
            errcode.HERR_INVALID_FACE_FEATURE,
            actual_dtype=str(data.dtype)
        )


def validate_session_initialized(session, operation: str = "Session operation"):
    """Validate if session is initialized"""
    if session is None or session._sess is None:
        raise ResourceError(
            f"{operation}: Session not initialized",
            errcode.HERR_INVALID_CONTEXT_HANDLE
        )


# === Exception handling decorators for special scenarios ===

def handle_c_api_errors(operation_name: str):
    """Decorator for wrapping C API calls"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                if not isinstance(e, InspireFaceError):
                    # Wrap non-InspireFace exceptions as ProcessingError
                    raise ProcessingError(
                        f"{operation_name}: {str(e)}",

View on GitHub (pinned to 7fadd420c2)

Solutions

  1. Recreate the session: param = SessionCustomParameter(); session = InspireFaceSession(param, ...)
  2. Ensure the original InspireFaceSession(...) constructor did not throw (launch/resource errors surface there)
  3. Scope usage: create the session once and stop using it after release(); guard with if session and session._sess is not None

Example fix

# before
session.release()
# ... later ...
session.face_detection(img)  # ResourceError
# after
session.release()
session = InspireFaceSession(SessionCustomParameter(), detect_mode=0, max_detect_num=10)
session.face_detection(img)
Defensive patterns

Strategy: validation

Validate before calling

assert session is not None and getattr(session, '_sess', None) is not None, 'session dead'

Type guard

def session_alive(sess) -> bool:
    return sess is not None and getattr(sess, '_sess', None) is not None

Try / catch

from inspireface.modules.exception import ResourceError
try:
    faces = session.face_detection(img)
except ResourceError:
    session = InspireFaceSession(SessionCustomParameter(), 0, 10)  # recreate
    faces = session.face_detection(img)

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of deepinsight/insightface@7fadd420c2 (2026-08-28). Data as JSON: /api/errors/26f4e5f1fee362e1. Report an issue: GitHub.