-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpy_nif.c
More file actions
7556 lines (6395 loc) · 255 KB
/
py_nif.c
File metadata and controls
7556 lines (6395 loc) · 255 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2026 Benoit Chesneau
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* py_nif.c - Python integration NIF for Erlang
*
* This NIF embeds Python and allows Erlang processes to execute Python code
* using dirty I/O schedulers. The design follows patterns from Granian:
*
* - GIL is released while waiting for Erlang messages
* - Workers run on dirty I/O schedulers
* - Type conversion between Erlang terms and Python objects
*
* Key patterns:
* - Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS around blocking ops
* - Resource types for Python objects to ensure proper cleanup
* - Dirty NIF flags for GIL-holding operations
*
* This file is the main entry point. It includes the following modules:
* - py_nif.h: Shared header with types and declarations
* - py_convert.c: Type conversion (Python <-> Erlang)
* - py_exec.c: Python execution and GIL management
* - py_callback.c: Callback system and asyncio support
*/
#include "py_nif.h"
#include "py_asgi.h"
#include "py_wsgi.h"
#include "py_event_loop.h"
#include "py_channel.h"
#include "py_buffer.h"
/* ============================================================================
* Global state definitions
* ============================================================================ */
ErlNifResourceType *WORKER_RESOURCE_TYPE = NULL;
ErlNifResourceType *PYOBJ_RESOURCE_TYPE = NULL;
/* ASYNC_WORKER_RESOURCE_TYPE removed - async workers replaced by event loop model */
ErlNifResourceType *SUSPENDED_STATE_RESOURCE_TYPE = NULL;
#ifdef HAVE_SUBINTERPRETERS
ErlNifResourceType *SUBINTERP_WORKER_RESOURCE_TYPE = NULL;
#endif
/* Process-per-context resource type (no mutex) */
ErlNifResourceType *PY_CONTEXT_RESOURCE_TYPE = NULL;
/* py_ref resource type (Python object with interp_id for auto-routing) */
ErlNifResourceType *PY_REF_RESOURCE_TYPE = NULL;
/* suspended_context_state_t resource type (context suspension for callbacks) */
ErlNifResourceType *PY_CONTEXT_SUSPENDED_RESOURCE_TYPE = NULL;
/* inline_continuation_t resource type (inline scheduler continuation) */
ErlNifResourceType *INLINE_CONTINUATION_RESOURCE_TYPE = NULL;
/* Process-local Python environment resource type */
ErlNifResourceType *PY_ENV_RESOURCE_TYPE = NULL;
/* Getter for PY_ENV_RESOURCE_TYPE (used by py_event_loop.c) */
ErlNifResourceType *get_env_resource_type(void) {
return PY_ENV_RESOURCE_TYPE;
}
_Atomic uint32_t g_context_id_counter = 1;
/* ============================================================================
* Process-local Python Environment
* ============================================================================
* Each Erlang process can have its own Python globals/locals dict via a NIF
* resource stored in the process dictionary. When the process exits, the
* resource destructor frees the Python dicts.
*/
/* py_env_resource_t is now defined in py_nif.h */
/**
* @brief Destructor for py_env_resource_t
*
* Called when the resource reference is garbage collected (process exits).
* Acquires GIL and decrefs the Python dicts.
*
* For subinterpreters, we must DECREF in the correct interpreter context.
* If the interpreter was destroyed (context freed), we skip DECREF since
* the objects were already freed with the interpreter.
*/
static void py_env_resource_dtor(ErlNifEnv *env, void *obj) {
(void)env;
py_env_resource_t *res = (py_env_resource_t *)obj;
if (!runtime_is_running()) {
res->globals = NULL;
res->locals = NULL;
return;
}
PyGILState_STATE gstate = PyGILState_Ensure();
#ifdef HAVE_SUBINTERPRETERS
if (res->pool_slot >= 0) {
/* Created in a shared-GIL subinterpreter - must DECREF in correct interpreter */
subinterp_slot_t *slot = subinterp_pool_get(res->pool_slot);
/* Verify slot is still valid and has same interpreter */
if (slot != NULL && slot->initialized && slot->interp != NULL) {
int64_t slot_interp_id = PyInterpreterState_GetID(slot->interp);
if (slot_interp_id == res->interp_id) {
/* Same interpreter, safe to DECREF */
PyThreadState *saved = PyThreadState_Swap(slot->tstate);
Py_XDECREF(res->globals);
Py_XDECREF(res->locals);
PyThreadState_Swap(saved);
}
/* If interp_id mismatch, slot was reused - skip DECREF */
}
/* If slot invalid/not initialized, interpreter destroyed - skip DECREF */
} else if (res->interp_id != 0) {
/* OWN_GIL subinterpreter: pool_slot == -1 but interp_id != 0
* These dicts were created in an OWN_GIL interpreter. We cannot safely
* DECREF them here because:
* 1. The interpreter might already be destroyed
* 2. We cannot switch to its thread state from this thread
* When the OWN_GIL context is destroyed, Py_EndInterpreter cleans up
* all objects, so we skip DECREF to avoid double-free or invalid access. */
} else
#endif
{
/* Main interpreter */
Py_XDECREF(res->globals);
Py_XDECREF(res->locals);
}
PyGILState_Release(gstate);
res->globals = NULL;
res->locals = NULL;
}
/* Invariant counters for debugging and leak detection */
py_invariant_counters_t g_counters = {0};
_Atomic py_runtime_state_t g_runtime_state = PY_STATE_UNINIT;
PyThreadState *g_main_thread_state = NULL;
/* Execution mode */
py_execution_mode_t g_execution_mode = PY_MODE_MULTI_EXECUTOR;
int g_num_executors = 4;
/* Multi-executor pool */
executor_t g_executors[MAX_EXECUTORS];
_Atomic int g_next_executor = 0;
_Atomic bool g_multi_executor_initialized = false;
/* Single executor state */
pthread_t g_executor_thread;
pthread_mutex_t g_executor_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_executor_cond = PTHREAD_COND_INITIALIZER;
py_request_t *g_executor_queue_head = NULL;
py_request_t *g_executor_queue_tail = NULL;
_Atomic bool g_executor_running = false;
_Atomic bool g_executor_shutdown = false;
/* Global counter for callback IDs */
_Atomic uint64_t g_callback_id_counter = 1;
/* Custom exception for suspension */
PyObject *SuspensionRequiredException = NULL;
/* Custom exception for dead/unreachable processes */
PyObject *ProcessErrorException = NULL;
/* Cached numpy.ndarray type for fast isinstance checks (NULL if numpy not available) */
PyObject *g_numpy_ndarray_type = NULL;
/* Thread-local callback context */
__thread py_worker_t *tl_current_worker = NULL;
__thread py_context_t *tl_current_context = NULL;
__thread ErlNifEnv *tl_callback_env = NULL;
__thread suspended_state_t *tl_current_suspended = NULL;
__thread suspended_context_state_t *tl_current_context_suspended = NULL;
__thread bool tl_allow_suspension = false;
/* Thread-local pending callback state (flag-based detection, not exception-based) */
__thread bool tl_pending_callback = false;
__thread uint64_t tl_pending_callback_id = 0;
__thread char *tl_pending_func_name = NULL;
__thread size_t tl_pending_func_name_len = 0;
__thread PyObject *tl_pending_args = NULL;
/**
* Clear all pending callback thread-local state.
*
* Must be called at context boundaries while still in the correct interpreter
* context, to prevent cross-interpreter contamination if Python code caught
* and swallowed SuspensionRequiredException.
*/
static inline void clear_pending_callback_tls(void) {
tl_pending_callback = false;
tl_pending_callback_id = 0;
if (tl_pending_func_name != NULL) {
enif_free(tl_pending_func_name);
tl_pending_func_name = NULL;
}
tl_pending_func_name_len = 0;
Py_CLEAR(tl_pending_args);
}
/* Thread-local timeout state */
__thread uint64_t tl_timeout_deadline = 0;
__thread bool tl_timeout_enabled = false;
/* Thread-local variable to track current local env during reentrant calls */
__thread py_env_resource_t *tl_current_local_env = NULL;
/* Atoms */
ERL_NIF_TERM ATOM_OK;
ERL_NIF_TERM ATOM_ERROR;
ERL_NIF_TERM ATOM_TRUE;
ERL_NIF_TERM ATOM_FALSE;
ERL_NIF_TERM ATOM_NONE;
ERL_NIF_TERM ATOM_NIL;
ERL_NIF_TERM ATOM_UNDEFINED;
ERL_NIF_TERM ATOM_NIF_NOT_LOADED;
ERL_NIF_TERM ATOM_GENERATOR;
ERL_NIF_TERM ATOM_STOP_ITERATION;
ERL_NIF_TERM ATOM_TIMEOUT;
ERL_NIF_TERM ATOM_NAN;
ERL_NIF_TERM ATOM_INFINITY;
ERL_NIF_TERM ATOM_NEG_INFINITY;
ERL_NIF_TERM ATOM_ERLANG_CALLBACK;
ERL_NIF_TERM ATOM_ASYNC_RESULT;
ERL_NIF_TERM ATOM_ASYNC_ERROR;
ERL_NIF_TERM ATOM_SUSPENDED;
ERL_NIF_TERM ATOM_SCHEDULE;
ERL_NIF_TERM ATOM_MORE;
/* Logging atoms */
ERL_NIF_TERM ATOM_PY_LOG;
ERL_NIF_TERM ATOM_SPAN_START;
ERL_NIF_TERM ATOM_SPAN_END;
ERL_NIF_TERM ATOM_SPAN_EVENT;
/* ============================================================================
* Forward declarations for cross-module functions
* ============================================================================ */
/* From py_callback.c - needed by py_exec.c */
static PyObject *build_pending_callback_exc_args(void);
static ERL_NIF_TERM build_suspended_result(ErlNifEnv *env, suspended_state_t *suspended);
/* Schedule marker type and helper - from py_callback.c, needed by py_exec.c */
typedef struct {
PyObject_HEAD
PyObject *callback_name; /* Registered callback name (string) */
PyObject *args; /* Arguments (tuple) */
} ScheduleMarkerObject;
static int is_schedule_marker(PyObject *obj);
/* Inline schedule marker type and helper - from py_callback.c, needed by py_exec.c */
typedef struct {
PyObject_HEAD
PyObject *module; /* Module name (string) */
PyObject *func; /* Function name (string) */
PyObject *args; /* Arguments (tuple or None) */
PyObject *kwargs; /* Keyword arguments (dict or None) */
PyObject *globals; /* Captured globals from caller's frame */
PyObject *locals; /* Captured locals from caller's frame */
} InlineScheduleMarkerObject;
static int is_inline_schedule_marker(PyObject *obj);
/* ============================================================================
* Include module implementations
* ============================================================================ */
#include "py_convert.c"
#include "py_exec.c"
#include "py_logging.c"
#include "py_callback.c"
#include "py_thread_worker.c"
#include "py_event_loop.c"
#include "py_asgi.c"
#include "py_wsgi.c"
#include "py_worker_pool.h"
#include "py_worker_pool.c"
#include "py_subinterp_pool.c"
#include "py_subinterp_thread.c"
#include "py_reactor_buffer.c"
#include "py_channel.c"
#include "py_buffer.c"
/* ============================================================================
* Resource callbacks
* ============================================================================ */
static void worker_destructor(ErlNifEnv *env, void *obj) {
(void)env;
py_worker_t *worker = (py_worker_t *)obj;
/* Close callback pipes */
if (worker->callback_pipe[0] >= 0) {
close(worker->callback_pipe[0]);
}
if (worker->callback_pipe[1] >= 0) {
close(worker->callback_pipe[1]);
}
/* Only clean up Python state if Python is still initialized */
if (worker->thread_state != NULL && runtime_is_running()) {
PyEval_RestoreThread(worker->thread_state);
Py_XDECREF(worker->globals);
Py_XDECREF(worker->locals);
PyThreadState_Clear(worker->thread_state);
PyThreadState_DeleteCurrent();
}
}
static void pyobj_destructor(ErlNifEnv *env, void *obj) {
(void)env;
py_object_t *wrapper = (py_object_t *)obj;
if (wrapper->obj != NULL && runtime_is_running()) {
#ifdef HAVE_SUBINTERPRETERS
/* For subinterpreter-owned objects (interp_id > 0):
* Objects are cleaned up by Py_EndInterpreter when context is destroyed.
* Skip eager cleanup here - let Python GC handle it.
*
* For main-interpreter objects (interp_id == 0):
* Safe to use PyGILState_Ensure for cleanup. */
if (wrapper->interp_id > 0) {
atomic_fetch_add(&g_counters.pyobj_destroyed, 1);
return;
}
#endif
/* Main interpreter (or no subinterpreters): safe to use PyGILState_Ensure */
PyThreadState *existing = PyGILState_GetThisThreadState();
if (existing != NULL || PyGILState_Check()) {
atomic_fetch_add(&g_counters.pyobj_destroyed, 1);
return;
}
PyGILState_STATE gstate = PyGILState_Ensure();
/* Skip DECREF for generators, coroutines, and async generators */
if (!PyGen_Check(wrapper->obj) && !PyCoro_CheckExact(wrapper->obj) &&
!PyAsyncGen_CheckExact(wrapper->obj)) {
Py_DECREF(wrapper->obj);
wrapper->obj = NULL;
}
PyGILState_Release(gstate);
}
atomic_fetch_add(&g_counters.pyobj_destroyed, 1);
}
/* async_worker_destructor removed - async workers replaced by event loop model */
#ifdef HAVE_SUBINTERPRETERS
static void subinterp_worker_destructor(ErlNifEnv *env, void *obj) {
(void)env;
py_subinterp_worker_t *worker = (py_subinterp_worker_t *)obj;
/* For OWN_GIL subinterpreters, we cannot safely acquire the GIL from the
* GC thread (destructor may run on any thread). PyGILState_Ensure only
* works for the main interpreter, and PyThreadState_Swap doesn't actually
* acquire the GIL.
*
* If the user didn't call the explicit destroy function, the subinterpreter
* leaks. This is a known limitation - users must call destroy explicitly. */
if (worker->tstate != NULL && runtime_is_running()) {
#ifdef DEBUG
fprintf(stderr, "Warning: subinterp_worker leaked - not destroyed "
"via explicit destroy. Use subinterp_worker_destroy/1.\n");
#endif
/* Skip Python cleanup - we can't safely acquire the subinterpreter's GIL */
worker->tstate = NULL;
worker->globals = NULL;
worker->locals = NULL;
}
/* Destroy the mutex */
pthread_mutex_destroy(&worker->mutex);
}
#endif
/**
* @brief Destructor for py_context_t (process-per-context)
*
* Safety net: If the context wasn't properly destroyed via nif_context_destroy,
* we attempt cleanup here. For subinterpreter mode, we release the pool slot.
*/
static void context_destructor(ErlNifEnv *env, void *obj) {
(void)env;
py_context_t *ctx = (py_context_t *)obj;
/* Close callback pipes if open */
if (ctx->callback_pipe[0] >= 0) {
close(ctx->callback_pipe[0]);
ctx->callback_pipe[0] = -1;
}
if (ctx->callback_pipe[1] >= 0) {
close(ctx->callback_pipe[1]);
ctx->callback_pipe[1] = -1;
}
/* Skip if already destroyed by nif_context_destroy */
if (ctx->destroyed) {
return;
}
#ifdef HAVE_SUBINTERPRETERS
/* For subinterpreter mode: clean up context's own dictionaries and release pool slot */
if (ctx->is_subinterp && ctx->pool_slot >= 0) {
/* Clean up Python objects with GIL */
if (runtime_is_running()) {
subinterp_slot_t *slot = subinterp_pool_get(ctx->pool_slot);
if (slot != NULL && slot->initialized) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyThreadState *saved = PyThreadState_Swap(slot->tstate);
Py_XDECREF(ctx->module_cache);
Py_XDECREF(ctx->globals);
Py_XDECREF(ctx->locals);
PyThreadState_Swap(saved);
PyGILState_Release(gstate);
}
}
ctx->module_cache = NULL;
ctx->globals = NULL;
ctx->locals = NULL;
subinterp_pool_free(ctx->pool_slot);
ctx->pool_slot = -1;
ctx->destroyed = true;
atomic_fetch_add(&g_counters.ctx_destroyed, 1);
return;
}
#endif
if (!runtime_is_running()) {
return;
}
#ifdef HAVE_SUBINTERPRETERS
/* Worker-mode contexts in HAVE_SUBINTERPRETERS builds: clean up
* Python dicts with GIL. */
if (PyGILState_GetThisThreadState() != NULL || PyGILState_Check()) {
return;
}
{
PyGILState_STATE gstate = PyGILState_Ensure();
Py_XDECREF(ctx->module_cache);
Py_XDECREF(ctx->globals);
Py_XDECREF(ctx->locals);
PyGILState_Release(gstate);
}
#else
/* Non-HAVE_SUBINTERPRETERS: all contexts are worker mode */
/* Worker mode: safe to use PyGILState_Ensure */
if (PyGILState_GetThisThreadState() != NULL || PyGILState_Check()) {
return;
}
PyGILState_STATE gstate = PyGILState_Ensure();
Py_XDECREF(ctx->module_cache);
Py_XDECREF(ctx->globals);
Py_XDECREF(ctx->locals);
if (ctx->thread_state != NULL) {
PyThreadState_Clear(ctx->thread_state);
PyThreadState_Delete(ctx->thread_state);
}
PyGILState_Release(gstate);
#endif
}
/**
* @brief Destructor for py_ref_t (Python object with interp_id)
*
* This destructor properly cleans up the Python object reference.
* The interp_id is used for routing but doesn't need cleanup.
*/
static void py_ref_destructor(ErlNifEnv *env, void *obj) {
(void)env;
py_ref_t *ref = (py_ref_t *)obj;
if (runtime_is_running() && ref->obj != NULL) {
#ifdef HAVE_SUBINTERPRETERS
/* For subinterpreter-owned objects (interp_id > 0):
* Objects are cleaned up by Py_EndInterpreter when context is destroyed.
*
* For main-interpreter objects (interp_id == 0):
* Safe to use PyGILState_Ensure for cleanup. */
if (ref->interp_id > 0) {
atomic_fetch_add(&g_counters.pyref_destroyed, 1);
return;
}
#endif
/* Main interpreter (or no subinterpreters): safe to use PyGILState_Ensure */
if (PyGILState_GetThisThreadState() != NULL || PyGILState_Check()) {
atomic_fetch_add(&g_counters.pyref_destroyed, 1);
return;
}
PyGILState_STATE gstate = PyGILState_Ensure();
/* Skip DECREF for generators, coroutines, and async generators */
if (!PyGen_Check(ref->obj) && !PyCoro_CheckExact(ref->obj) &&
!PyAsyncGen_CheckExact(ref->obj)) {
Py_XDECREF(ref->obj);
ref->obj = NULL;
}
PyGILState_Release(gstate);
}
atomic_fetch_add(&g_counters.pyref_destroyed, 1);
}
/**
* @brief Destructor for suspended_context_state_t
*
* Cleans up all resources associated with a suspended context state.
*/
static void suspended_context_state_destructor(ErlNifEnv *env, void *obj) {
(void)env;
suspended_context_state_t *state = (suspended_context_state_t *)obj;
/* Clean up Python objects if Python is still initialized */
if (runtime_is_running() && state->callback_args != NULL) {
#ifdef HAVE_SUBINTERPRETERS
/* For subinterpreter contexts: defer cleanup to Py_EndInterpreter.
* For main-interpreter contexts: safe to use PyGILState_Ensure. */
if (state->ctx != NULL && state->ctx->is_subinterp) {
state->callback_args = NULL;
} else
#endif
{
/* Main interpreter (or no subinterpreters): safe to use PyGILState_Ensure */
if (PyGILState_GetThisThreadState() != NULL || PyGILState_Check()) {
state->callback_args = NULL;
} else {
PyGILState_STATE gstate = PyGILState_Ensure();
Py_XDECREF(state->callback_args);
state->callback_args = NULL;
PyGILState_Release(gstate);
}
}
}
/* Free allocated memory */
if (state->callback_func_name != NULL) {
enif_free(state->callback_func_name);
}
if (state->result_data != NULL) {
enif_free(state->result_data);
}
/* Free sequential callback results array */
if (state->callback_results != NULL) {
for (size_t i = 0; i < state->num_callback_results; i++) {
if (state->callback_results[i].data != NULL) {
enif_free(state->callback_results[i].data);
}
}
enif_free(state->callback_results);
}
/* Free original context environment */
if (state->orig_env != NULL) {
enif_free_env(state->orig_env);
}
/* Release binaries */
if (state->orig_module.data != NULL) {
enif_release_binary(&state->orig_module);
}
if (state->orig_func.data != NULL) {
enif_release_binary(&state->orig_func);
}
if (state->orig_code.data != NULL) {
enif_release_binary(&state->orig_code);
}
/* Release the context resource (was kept in create_suspended_context_state_*) */
if (state->ctx != NULL) {
enif_release_resource(state->ctx);
state->ctx = NULL;
}
atomic_fetch_add(&g_counters.suspended_destroyed, 1);
}
static void suspended_state_destructor(ErlNifEnv *env, void *obj) {
(void)env;
suspended_state_t *state = (suspended_state_t *)obj;
/* Clean up Python objects if Python is still initialized.
* suspended_state_t is used with the worker-based API which runs in
* the main interpreter, so we always use PyGILState_Ensure. */
if (runtime_is_running() && state->callback_args != NULL) {
if (PyGILState_GetThisThreadState() != NULL || PyGILState_Check()) {
state->callback_args = NULL;
} else {
PyGILState_STATE gstate = PyGILState_Ensure();
Py_XDECREF(state->callback_args);
state->callback_args = NULL;
PyGILState_Release(gstate);
}
}
/* Free allocated memory */
if (state->callback_func_name != NULL) {
enif_free(state->callback_func_name);
state->callback_func_name = NULL;
}
if (state->result_data != NULL) {
enif_free(state->result_data);
state->result_data = NULL;
}
/* Free original context environment */
if (state->orig_env != NULL) {
enif_free_env(state->orig_env);
state->orig_env = NULL;
}
/* Destroy synchronization primitives */
pthread_mutex_destroy(&state->mutex);
pthread_cond_destroy(&state->cond);
atomic_fetch_add(&g_counters.suspended_destroyed, 1);
}
/* ============================================================================
* Inline Continuation Support
* ============================================================================
*
* Inline continuations allow Python functions to chain directly via
* enif_schedule_nif() without returning to Erlang messaging.
*/
/**
* @brief Destructor for inline_continuation_t resource
*
* Frees all resources associated with an inline continuation.
*/
static void inline_continuation_destructor(ErlNifEnv *env, void *obj) {
(void)env;
inline_continuation_t *cont = (inline_continuation_t *)obj;
/* Free string allocations */
if (cont->module_name != NULL) {
enif_free(cont->module_name);
cont->module_name = NULL;
}
if (cont->func_name != NULL) {
enif_free(cont->func_name);
cont->func_name = NULL;
}
/* Clean up Python objects if Python is still initialized */
if (runtime_is_running() && (cont->args != NULL || cont->kwargs != NULL ||
cont->globals != NULL || cont->locals != NULL)) {
/* For subinterpreter contexts: defer cleanup to Py_EndInterpreter */
#ifdef HAVE_SUBINTERPRETERS
if (cont->ctx != NULL && cont->ctx->is_subinterp) {
cont->args = NULL;
cont->kwargs = NULL;
cont->globals = NULL;
cont->locals = NULL;
} else
#endif
{
/* Main interpreter: safe to use PyGILState_Ensure */
if (PyGILState_GetThisThreadState() == NULL && !PyGILState_Check()) {
PyGILState_STATE gstate = PyGILState_Ensure();
Py_XDECREF(cont->args);
Py_XDECREF(cont->kwargs);
Py_XDECREF(cont->globals);
Py_XDECREF(cont->locals);
cont->args = NULL;
cont->kwargs = NULL;
cont->globals = NULL;
cont->locals = NULL;
PyGILState_Release(gstate);
} else {
cont->args = NULL;
cont->kwargs = NULL;
cont->globals = NULL;
cont->locals = NULL;
}
}
}
/* Release the context resource if held */
if (cont->ctx != NULL) {
enif_release_resource(cont->ctx);
cont->ctx = NULL;
}
/* Release the local_env resource if held */
if (cont->local_env != NULL) {
enif_release_resource(cont->local_env);
cont->local_env = NULL;
}
}
/**
* @brief Create an inline continuation resource
*
* @param ctx Context for execution (will be kept)
* @param local_env Optional process-local environment (will be kept if non-NULL)
* @param marker The InlineScheduleMarker containing call info
* @param depth Current continuation depth
* @return inline_continuation_t* or NULL on failure
*
* @note Caller must release the resource when done
*/
static inline_continuation_t *create_inline_continuation(
py_context_t *ctx,
void *local_env, /* py_env_resource_t* */
PyObject *marker_obj,
uint32_t depth) {
InlineScheduleMarkerObject *marker = (InlineScheduleMarkerObject *)marker_obj;
inline_continuation_t *cont = enif_alloc_resource(
INLINE_CONTINUATION_RESOURCE_TYPE, sizeof(inline_continuation_t));
if (cont == NULL) {
return NULL;
}
memset(cont, 0, sizeof(inline_continuation_t));
/* Copy module name */
Py_ssize_t module_len;
const char *module_str = PyUnicode_AsUTF8AndSize(marker->module, &module_len);
if (module_str == NULL) {
enif_release_resource(cont);
return NULL;
}
cont->module_name = enif_alloc(module_len + 1);
if (cont->module_name == NULL) {
enif_release_resource(cont);
return NULL;
}
memcpy(cont->module_name, module_str, module_len);
cont->module_name[module_len] = '\0';
cont->module_len = module_len;
/* Copy func name */
Py_ssize_t func_len;
const char *func_str = PyUnicode_AsUTF8AndSize(marker->func, &func_len);
if (func_str == NULL) {
enif_release_resource(cont);
return NULL;
}
cont->func_name = enif_alloc(func_len + 1);
if (cont->func_name == NULL) {
enif_release_resource(cont);
return NULL;
}
memcpy(cont->func_name, func_str, func_len);
cont->func_name[func_len] = '\0';
cont->func_len = func_len;
/* INCREF args and kwargs */
if (marker->args != Py_None) {
Py_INCREF(marker->args);
cont->args = marker->args;
} else {
cont->args = NULL;
}
if (marker->kwargs != Py_None) {
Py_INCREF(marker->kwargs);
cont->kwargs = marker->kwargs;
} else {
cont->kwargs = NULL;
}
/* Store captured globals and locals */
if (marker->globals != NULL) {
Py_INCREF(marker->globals);
cont->globals = marker->globals;
} else {
cont->globals = NULL;
}
if (marker->locals != NULL) {
Py_INCREF(marker->locals);
cont->locals = marker->locals;
} else {
cont->locals = NULL;
}
/* Store context (keep resource reference) */
cont->ctx = ctx;
enif_keep_resource(ctx);
/* Store local_env if provided */
if (local_env != NULL) {
cont->local_env = local_env;
enif_keep_resource(local_env);
}
cont->depth = depth;
cont->interp_id = ctx->interp_id;
return cont;
}
/**
* @brief NIF: Execute inline continuation
*
* This is the continuation function called by enif_schedule_nif().
* It executes the Python function and handles the result:
* - InlineScheduleMarker: chain via another enif_schedule_nif
* - ScheduleMarker: return {schedule, ...} to Erlang
* - Suspension: return {suspended, ...} to Erlang
* - Normal result: return {ok, Result}
*/
static ERL_NIF_TERM nif_inline_continuation(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) {
(void)argc;
inline_continuation_t *cont;
if (!enif_get_resource(env, argv[0], INLINE_CONTINUATION_RESOURCE_TYPE, (void **)&cont)) {
return make_error(env, "invalid_continuation");
}
if (!runtime_is_running()) {
return make_error(env, "python_not_running");
}
/* Check depth limit */
if (cont->depth >= MAX_INLINE_CONTINUATION_DEPTH) {
return make_error(env, "inline_continuation_depth_exceeded");
}
py_context_t *ctx = cont->ctx;
if (ctx == NULL || ctx->destroyed) {
return make_error(env, "context_destroyed");
}
/* Acquire thread state */
py_context_guard_t guard = py_context_acquire(ctx);
if (!guard.acquired) {
return make_error(env, "acquire_failed");
}
/* Set thread-local context for callback support */
py_context_t *prev_context = tl_current_context;
tl_current_context = ctx;
/* Enable suspension for callback support */
bool prev_allow_suspension = tl_allow_suspension;
tl_allow_suspension = true;
/* Set callback env for consume_time_slice */
ErlNifEnv *prev_callback_env = tl_callback_env;
tl_callback_env = env;
ERL_NIF_TERM result;
/* Import module and get function */
PyObject *func = NULL;
PyObject *module = NULL;
/* Priority for __main__ lookups:
* 1. Captured globals/locals from the marker (caller's frame)
* 2. local_env globals (process-local environment)
* 3. ctx->globals/locals (context defaults)
*/
py_env_resource_t *local_env = (py_env_resource_t *)cont->local_env;
if (strcmp(cont->module_name, "__main__") == 0) {
/* Try captured globals first (from caller's frame) */
if (cont->globals != NULL) {
func = PyDict_GetItemString(cont->globals, cont->func_name);
}
/* Try captured locals */
if (func == NULL && cont->locals != NULL) {
func = PyDict_GetItemString(cont->locals, cont->func_name);
}
/* Fallback to local_env globals */
if (func == NULL && local_env != NULL) {
func = PyDict_GetItemString(local_env->globals, cont->func_name);
}
/* Fallback to context globals/locals */
if (func == NULL) {
func = PyDict_GetItemString(ctx->globals, cont->func_name);
}
if (func == NULL) {
func = PyDict_GetItemString(ctx->locals, cont->func_name);
}
if (func != NULL) {
Py_INCREF(func);
} else {
PyErr_Format(PyExc_NameError, "name '%s' is not defined", cont->func_name);
}
} else {
module = PyImport_ImportModule(cont->module_name);
if (module != NULL) {
func = PyObject_GetAttrString(module, cont->func_name);
Py_DECREF(module);
}
}
if (func == NULL) {
result = make_py_error(env);
goto cleanup;
}
/* Build args tuple */
PyObject *args = cont->args;
if (args == NULL) {
args = PyTuple_New(0);
if (args == NULL) {
Py_DECREF(func);
result = make_py_error(env);
goto cleanup;
}
} else {
Py_INCREF(args);
}
/* Get kwargs */
PyObject *kwargs = cont->kwargs;
/* Call the function */
PyObject *py_result = PyObject_Call(func, args, kwargs);
Py_DECREF(func);
Py_DECREF(args);
if (py_result == NULL) {
/* Check for pending callback */
if (tl_pending_callback) {
PyErr_Clear();
/* Create suspended context state for callback handling */
ErlNifBinary module_bin, func_bin;
enif_alloc_binary(cont->module_len, &module_bin);
memcpy(module_bin.data, cont->module_name, cont->module_len);
enif_alloc_binary(cont->func_len, &func_bin);
memcpy(func_bin.data, cont->func_name, cont->func_len);
/* Convert args to Erlang term for replay */
ERL_NIF_TERM args_term = enif_make_list(env, 0);
if (cont->args != NULL) {
args_term = py_to_term(env, cont->args);
}
ERL_NIF_TERM kwargs_term = enif_make_new_map(env);
if (cont->kwargs != NULL) {
kwargs_term = py_to_term(env, cont->kwargs);
}
suspended_context_state_t *suspended = create_suspended_context_state_for_call(
env, ctx, &module_bin, &func_bin, args_term, kwargs_term);
enif_release_binary(&module_bin);
enif_release_binary(&func_bin);
if (suspended == NULL) {
tl_pending_callback = false;
Py_CLEAR(tl_pending_args);
result = make_error(env, "create_suspended_state_failed");
} else {
result = build_suspended_context_result(env, suspended);
}
} else {
result = make_py_error(env);
}
} else if (is_inline_schedule_marker(py_result)) {
/* Chain via another enif_schedule_nif */
inline_continuation_t *next_cont = create_inline_continuation(
ctx, cont->local_env, py_result, cont->depth + 1);
Py_DECREF(py_result);
if (next_cont == NULL) {
result = make_error(env, "create_continuation_failed");
} else {
ERL_NIF_TERM cont_ref = enif_make_resource(env, next_cont);
enif_release_resource(next_cont);
/* Restore thread-local state before scheduling */
tl_allow_suspension = prev_allow_suspension;
tl_current_context = prev_context;
tl_callback_env = prev_callback_env;
clear_pending_callback_tls();