quapp-common 0.0.16.dev2__tar.gz → 0.0.17.dev2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. {quapp_common-0.0.16.dev2/quapp_common.egg-info → quapp_common-0.0.17.dev2}/PKG-INFO +60 -2
  2. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/README.md +58 -0
  3. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/pyproject.toml +4 -2
  4. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/async_tasks/async_invocation_task.py +43 -6
  5. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/job_heartbeat.py +2 -2
  6. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/job_manager.py +2 -2
  7. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/callback/update_job_metadata.py +19 -2
  8. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/config/logging_config.py +42 -7
  9. quapp_common-0.0.17.dev2/quapp_common/joblog/__init__.py +3 -0
  10. quapp_common-0.0.17.dev2/quapp_common/joblog/capture.py +118 -0
  11. quapp_common-0.0.17.dev2/quapp_common/joblog/child.py +109 -0
  12. quapp_common-0.0.17.dev2/quapp_common/joblog/ingest.py +179 -0
  13. quapp_common-0.0.17.dev2/quapp_common/joblog/pipes.py +92 -0
  14. quapp_common-0.0.17.dev2/quapp_common/joblog/shipper.py +510 -0
  15. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/process_utils.py +9 -0
  16. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2/quapp_common.egg-info}/PKG-INFO +60 -2
  17. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common.egg-info/SOURCES.txt +7 -0
  18. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common.egg-info/requires.txt +1 -1
  19. quapp_common-0.0.17.dev2/tests/test_job_log_capture.py +716 -0
  20. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/LICENSE +0 -0
  21. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/__init__.py +0 -0
  22. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/async_tasks/__init__.py +0 -0
  23. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/async_tasks/async_task.py +0 -0
  24. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/async_tasks/export_circuit_task.py +0 -0
  25. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/async_tasks/post_processing_task.py +0 -0
  26. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/__init__.py +0 -0
  27. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/__init__.py +0 -0
  28. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/invocation.py +0 -0
  29. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/job_fetcher.py +0 -0
  30. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/backend/job_fetching.py +0 -0
  31. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/bridge.py +0 -0
  32. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/callback/__init__.py +0 -0
  33. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/circuit_adapter.py +0 -0
  34. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/device/__init__.py +0 -0
  35. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/device/device_selection.py +0 -0
  36. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/dispatcher.py +0 -0
  37. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/component/result_serializer.py +0 -0
  38. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/config/__init__.py +0 -0
  39. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/config/log_context.py +0 -0
  40. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/config/thread_config.py +0 -0
  41. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/__init__.py +0 -0
  42. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/async_task/__init__.py +0 -0
  43. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/async_task/circuit_export/__init__.py +0 -0
  44. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/async_task/circuit_export/backend_holder.py +0 -0
  45. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/async_task/circuit_export/circuit_holder.py +0 -0
  46. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/backend/__init__.py +0 -0
  47. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/backend/backend_information.py +0 -0
  48. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/callback/__init__.py +0 -0
  49. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/callback/callback_url.py +0 -0
  50. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/device/__init__.py +0 -0
  51. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/device/circuit_running_option.py +0 -0
  52. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/promise/__init__.py +0 -0
  53. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/promise/post_processing_promise.py +0 -0
  54. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/promise/promise.py +0 -0
  55. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/request/__init__.py +0 -0
  56. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/request/invocation_request.py +0 -0
  57. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/request/job_fetching_request.py +0 -0
  58. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/request/request.py +0 -0
  59. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/response/__init__.py +0 -0
  60. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/response/authentication.py +0 -0
  61. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/response/custom_header.py +0 -0
  62. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/response/error_report.py +0 -0
  63. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/data/response/job_response.py +0 -0
  64. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/__init__.py +0 -0
  65. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/base_enum.py +0 -0
  66. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/error_category.py +0 -0
  67. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/http_header.py +0 -0
  68. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/invocation_step.py +0 -0
  69. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/language.py +0 -0
  70. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/media_type.py +0 -0
  71. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/processing_unit.py +0 -0
  72. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/provider_tag.py +0 -0
  73. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/runtime_phase.py +0 -0
  74. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/sdk.py +0 -0
  75. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/status/__init__.py +0 -0
  76. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/status/job_status.py +0 -0
  77. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/status/status_code.py +0 -0
  78. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/enum/token_type.py +0 -0
  79. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/factory/__init__.py +0 -0
  80. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/factory/device_factory.py +0 -0
  81. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/factory/handler_factory.py +0 -0
  82. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/factory/provider_factory.py +0 -0
  83. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/handler/__init__.py +0 -0
  84. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/handler/handler.py +0 -0
  85. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/__init__.py +0 -0
  86. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/device/__init__.py +0 -0
  87. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/device/custom_device.py +0 -0
  88. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/device/device.py +0 -0
  89. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/invocation.py +0 -0
  90. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/provider/__init__.py +0 -0
  91. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/model/provider/provider.py +0 -0
  92. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/__init__.py +0 -0
  93. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/error_classifier.py +0 -0
  94. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/file_utils.py +0 -0
  95. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/http_utils.py +0 -0
  96. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/invocation_failure.py +0 -0
  97. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/json_parser_utils.py +0 -0
  98. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common/util/response_utils.py +0 -0
  99. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common.egg-info/dependency_links.txt +0 -0
  100. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/quapp_common.egg-info/top_level.txt +0 -0
  101. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/setup.cfg +0 -0
  102. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_callback_payload.py +0 -0
  103. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_circuit_adapter.py +0 -0
  104. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_compute_process.py +0 -0
  105. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_dispatcher_runner_error.py +0 -0
  106. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_error_classifier.py +0 -0
  107. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_error_log_dedupe.py +0 -0
  108. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_error_report.py +0 -0
  109. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_fork_socket_inheritance.py +0 -0
  110. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_invocation_failure.py +0 -0
  111. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_job_heartbeat.py +0 -0
  112. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_json_parser_utils.py +0 -0
  113. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_language_dispatcher.py +0 -0
  114. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_log_secret_leak.py +0 -0
  115. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_logging_config.py +0 -0
  116. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_no_sdk_dependency.py +0 -0
  117. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_phase_coverage.py +0 -0
  118. {quapp_common-0.0.16.dev2 → quapp_common-0.0.17.dev2}/tests/test_result_serializer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quapp-common
3
- Version: 0.0.16.dev2
3
+ Version: 0.0.17.dev2
4
4
  Summary: Quapp common library supporting Quapp Platform for Quantum Computing
5
5
  Author-email: "CITYNOW Co. Ltd. " <corp@citynow.vn>
6
6
  License: The MIT License (MIT)
@@ -19,7 +19,7 @@ Classifier: Programming Language :: Python :: 3
19
19
  Requires-Python: >=3.7
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
- Requires-Dist: loguru
22
+ Requires-Dist: loguru>=0.5.3
23
23
  Requires-Dist: requests
24
24
  Requires-Dist: numpy
25
25
  Requires-Dist: matplotlib
@@ -111,6 +111,64 @@ Notes:
111
111
 
112
112
  ## Recently Changes Highlights
113
113
 
114
+ ### v0.0.17.dev2 — Sửa server treo khi fork lúc đang ghi log
115
+
116
+ Sink loguru của process server (`configure_logging`) đổi từ `enqueue=True` sang
117
+ `enqueue=False`.
118
+
119
+ - **Lỗi:** với `enqueue=True`, hook at-fork của loguru khoá các lock của handler
120
+ theo thứ tự tuỳ ý (`WeakSet`). Khi nó cầm lock hàng đợi rồi chờ lock của handler,
121
+ trong khi một luồng khác đang giữ lock đó và chờ hàng đợi có chỗ (pipe hàng đợi
122
+ đầy), còn luồng xả hàng đợi lại chờ lock hàng đợi, thì fork không bao giờ trả về:
123
+ server treo ngay lúc tạo compute process, heartbeat hoặc `SyncManager`. Có từ
124
+ `0.0.15` (fork mỗi job); loguru 0.7.3 vẫn còn lỗi này.
125
+ - **Sửa:** ghi thẳng ra stderr, không còn luồng xả hàng đợi nên không còn vòng chờ.
126
+ Traceback vẫn được format sẵn trong filter. Đổi lại, dòng log dài hơn 4 KB
127
+ (`PIPE_BUF`) từ nhiều process ghi cùng lúc có thể xen nhau trong log container;
128
+ log job (PQF-23860) đi qua pipe riêng từng job nên không bị.
129
+ - **Test:** `test_server_sinks_write_without_a_queue` và
130
+ `test_forking_many_times_while_the_parent_logs_never_hangs` (30 lần fork trong
131
+ luồng phụ, treo thì fail thay vì treo cả bộ test). Trên code cũ: treo 9/40 lần ở
132
+ test fork 10 lần; stress test bắt được ở 2/3 lần chạy.
133
+
134
+ ### v0.0.17.dev1 — Log job trực tiếp về backend (PQF-23860)
135
+
136
+ Runtime đẩy log của từng job về backend trong lúc job chạy. Loki vẫn là đường dự
137
+ phòng.
138
+
139
+ - **Chỉ bật khi payload có `logIngest`.** Backend gắn block này khi bật
140
+ `INVOCATION_LOGGING_PUSH_ENABLED`. Không có block thì runtime chạy y như bản cũ:
141
+ không pipe, không tiền tố, không gọi mạng. Vì vậy template khai báo
142
+ `quapp-common>=…` lỡ cài bản này ở môi trường chưa bật tính năng cũng không đổi
143
+ hành vi.
144
+ - **Tiến trình compute** (`run_compute`): fd 1 và 2 trỏ vào một pipe riêng của job
145
+ (một pipe nên giữ đúng thứ tự stdout/stderr). `sys.stdout` / `sys.stderr` được
146
+ dựng mới, vì object kế thừa có thể mang lock bị luồng của tiến trình cha giữ lúc
147
+ fork và làm treo lần ghi đầu. Sink loguru được dựng lại trên `sys.stderr` mới,
148
+ `colorize=False`. Khi job xong: đóng pool, flush, rồi `fflush(NULL)` để không mất
149
+ dòng `printf` của code native trước `os._exit`.
150
+ - **Tiến trình server** (`quapp_common/joblog/shipper.py`): một luồng đọc pipe, ghi
151
+ từng dòng ra log container với tiền tố `[ConsoleJobLog][<jobId>]` (trừ dòng đã có
152
+ tag của job hoặc dòng JSON loguru của job), và một luồng gửi chunk về backend:
153
+ cắt ở `\n`, tối đa 256KB, mỗi 2s; lỗi mạng / 5xx / 429 thì gửi lại cùng `seq`;
154
+ mọi 4xx khác và outcome `TRUNCATED` / `SEALED` / `TOO_LATE` thì dừng gửi, chỉ
155
+ còn log container. `close` khi có cả EOF lẫn exit code; tiến trình cháu giữ pipe
156
+ quá 5s thì `close` với `abandoned`. Server tắt (atexit): gửi nốt rồi `close`
157
+ `abandoned`.
158
+ - **Tiến trình lấy kết quả** (payload có `providerJobId`): giữ log lại; nếu không
159
+ gọi callback nào và thoát mã 0 thì đó chỉ là một lần poll, writer được `close`
160
+ `discarded` mà không `open`.
161
+ - **Callback** (`update_job_metadata`): mang `X-Quapp-Log-Writer` +
162
+ `X-Quapp-Log-Token` trong tiến trình có capture, và đếm số lần thử gọi.
163
+ - **Fd thừa**: tiến trình compute, heartbeat và SyncManager đóng pipe của job khác
164
+ (`quapp_common/joblog/pipes.py`, khoá + `os.register_at_fork`).
165
+ - `loguru>=0.5.3`: từ bản này `Handler.stop()` bỏ qua handler của tiến trình khác,
166
+ nên tiến trình con gọi `logger.remove()` an toàn.
167
+
168
+ Test: `tests/test_job_log_capture.py` (33 test, gồm fork thật với một ingest server
169
+ giả). Đã chạy trên Python 3.11 (126 test của các vùng liên quan pass) và với
170
+ `loguru==0.5.3`.
171
+
114
172
  ### v0.0.14.dev5 — Gỡ toàn bộ dependency SDK lượng tử
115
173
 
116
174
  `quapp-common` không còn phụ thuộc SDK nào. SDK thuộc về lib con.
@@ -73,6 +73,64 @@ Notes:
73
73
 
74
74
  ## Recently Changes Highlights
75
75
 
76
+ ### v0.0.17.dev2 — Sửa server treo khi fork lúc đang ghi log
77
+
78
+ Sink loguru của process server (`configure_logging`) đổi từ `enqueue=True` sang
79
+ `enqueue=False`.
80
+
81
+ - **Lỗi:** với `enqueue=True`, hook at-fork của loguru khoá các lock của handler
82
+ theo thứ tự tuỳ ý (`WeakSet`). Khi nó cầm lock hàng đợi rồi chờ lock của handler,
83
+ trong khi một luồng khác đang giữ lock đó và chờ hàng đợi có chỗ (pipe hàng đợi
84
+ đầy), còn luồng xả hàng đợi lại chờ lock hàng đợi, thì fork không bao giờ trả về:
85
+ server treo ngay lúc tạo compute process, heartbeat hoặc `SyncManager`. Có từ
86
+ `0.0.15` (fork mỗi job); loguru 0.7.3 vẫn còn lỗi này.
87
+ - **Sửa:** ghi thẳng ra stderr, không còn luồng xả hàng đợi nên không còn vòng chờ.
88
+ Traceback vẫn được format sẵn trong filter. Đổi lại, dòng log dài hơn 4 KB
89
+ (`PIPE_BUF`) từ nhiều process ghi cùng lúc có thể xen nhau trong log container;
90
+ log job (PQF-23860) đi qua pipe riêng từng job nên không bị.
91
+ - **Test:** `test_server_sinks_write_without_a_queue` và
92
+ `test_forking_many_times_while_the_parent_logs_never_hangs` (30 lần fork trong
93
+ luồng phụ, treo thì fail thay vì treo cả bộ test). Trên code cũ: treo 9/40 lần ở
94
+ test fork 10 lần; stress test bắt được ở 2/3 lần chạy.
95
+
96
+ ### v0.0.17.dev1 — Log job trực tiếp về backend (PQF-23860)
97
+
98
+ Runtime đẩy log của từng job về backend trong lúc job chạy. Loki vẫn là đường dự
99
+ phòng.
100
+
101
+ - **Chỉ bật khi payload có `logIngest`.** Backend gắn block này khi bật
102
+ `INVOCATION_LOGGING_PUSH_ENABLED`. Không có block thì runtime chạy y như bản cũ:
103
+ không pipe, không tiền tố, không gọi mạng. Vì vậy template khai báo
104
+ `quapp-common>=…` lỡ cài bản này ở môi trường chưa bật tính năng cũng không đổi
105
+ hành vi.
106
+ - **Tiến trình compute** (`run_compute`): fd 1 và 2 trỏ vào một pipe riêng của job
107
+ (một pipe nên giữ đúng thứ tự stdout/stderr). `sys.stdout` / `sys.stderr` được
108
+ dựng mới, vì object kế thừa có thể mang lock bị luồng của tiến trình cha giữ lúc
109
+ fork và làm treo lần ghi đầu. Sink loguru được dựng lại trên `sys.stderr` mới,
110
+ `colorize=False`. Khi job xong: đóng pool, flush, rồi `fflush(NULL)` để không mất
111
+ dòng `printf` của code native trước `os._exit`.
112
+ - **Tiến trình server** (`quapp_common/joblog/shipper.py`): một luồng đọc pipe, ghi
113
+ từng dòng ra log container với tiền tố `[ConsoleJobLog][<jobId>]` (trừ dòng đã có
114
+ tag của job hoặc dòng JSON loguru của job), và một luồng gửi chunk về backend:
115
+ cắt ở `\n`, tối đa 256KB, mỗi 2s; lỗi mạng / 5xx / 429 thì gửi lại cùng `seq`;
116
+ mọi 4xx khác và outcome `TRUNCATED` / `SEALED` / `TOO_LATE` thì dừng gửi, chỉ
117
+ còn log container. `close` khi có cả EOF lẫn exit code; tiến trình cháu giữ pipe
118
+ quá 5s thì `close` với `abandoned`. Server tắt (atexit): gửi nốt rồi `close`
119
+ `abandoned`.
120
+ - **Tiến trình lấy kết quả** (payload có `providerJobId`): giữ log lại; nếu không
121
+ gọi callback nào và thoát mã 0 thì đó chỉ là một lần poll, writer được `close`
122
+ `discarded` mà không `open`.
123
+ - **Callback** (`update_job_metadata`): mang `X-Quapp-Log-Writer` +
124
+ `X-Quapp-Log-Token` trong tiến trình có capture, và đếm số lần thử gọi.
125
+ - **Fd thừa**: tiến trình compute, heartbeat và SyncManager đóng pipe của job khác
126
+ (`quapp_common/joblog/pipes.py`, khoá + `os.register_at_fork`).
127
+ - `loguru>=0.5.3`: từ bản này `Handler.stop()` bỏ qua handler của tiến trình khác,
128
+ nên tiến trình con gọi `logger.remove()` an toàn.
129
+
130
+ Test: `tests/test_job_log_capture.py` (33 test, gồm fork thật với một ingest server
131
+ giả). Đã chạy trên Python 3.11 (126 test của các vùng liên quan pass) và với
132
+ `loguru==0.5.3`.
133
+
76
134
  ### v0.0.14.dev5 — Gỡ toàn bộ dependency SDK lượng tử
77
135
 
78
136
  `quapp-common` không còn phụ thuộc SDK nào. SDK thuộc về lib con.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quapp-common"
7
- version = "0.0.16.dev2"
7
+ version = "0.0.17.dev2"
8
8
  description = "Quapp common library supporting Quapp Platform for Quantum Computing"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "CITYNOW Co. Ltd. ", email = "corp@citynow.vn" }]
@@ -24,7 +24,9 @@ keywords = ["quapp", "quapp-common", "quantum"]
24
24
  # đột version thật (pytket/lark, pennylane-rigetti/pyquil), và bắt mọi function
25
25
  # tải cả 6 SDK dù chỉ dùng một.
26
26
  dependencies = [
27
- "loguru",
27
+ # >=0.5.3: Handler.stop() skips handlers of another process, so a forked
28
+ # compute process can logger.remove() its inherited sinks (PQF-23860).
29
+ "loguru>=0.5.3",
28
30
  "requests",
29
31
  "numpy",
30
32
  "matplotlib",
@@ -17,6 +17,9 @@ from ..component.backend.job_manager import JobManager
17
17
  from ..config.log_context import bind_job
18
18
  from ..config.logging_config import logger
19
19
  from ..factory.handler_factory import HandlerFactory
20
+ from ..joblog import child as job_log_child
21
+ from ..joblog import pipes as job_log_pipes
22
+ from ..joblog.capture import JobLogCapture
20
23
  from ..model.invocation import Event, Error, Success
21
24
  from ..util.invocation_failure import report_invocation_failure
22
25
  from ..util.process_utils import release_inherited_server_sockets
@@ -62,7 +65,17 @@ def _watch_parent(parent_pid: int) -> None:
62
65
  time.sleep(PARENT_POLL_SEC)
63
66
 
64
67
 
65
- def run_compute(parent_pid: int, target) -> None:
68
+ def run_compute(parent_pid: int, target, capture_setup=None) -> None:
69
+ """Body of the compute process.
70
+
71
+ @param capture_setup: JobLogCapture.child_setup when the job's log is
72
+ captured (PQF-23860); it points fd 1/2 at the job's pipe before anything
73
+ else runs. None keeps the old behaviour.
74
+ """
75
+ if capture_setup is not None:
76
+ capture_setup()
77
+ else:
78
+ job_log_pipes.release_inherited()
66
79
  release_inherited_server_sockets()
67
80
  signal.signal(signal.SIGTERM, signal.SIG_DFL)
68
81
 
@@ -80,7 +93,15 @@ def run_compute(parent_pid: int, target) -> None:
80
93
  name='compute-parent-watch', daemon=True)
81
94
  watcher.start()
82
95
 
83
- target()
96
+ if capture_setup is None:
97
+ target()
98
+ return
99
+ try:
100
+ target()
101
+ finally:
102
+ # The process ends with os._exit: drain the pools, then flush Python's
103
+ # and libc's buffers so the last lines reach the pipe.
104
+ job_log_child.finish()
84
105
 
85
106
 
86
107
  class AsyncInvocationTask(AsyncTask):
@@ -125,7 +146,8 @@ class AsyncInvocationTask(AsyncTask):
125
146
  response is returned.
126
147
  """
127
148
  try:
128
- job_id = self.event.json().get('jobId')
149
+ payload = self.event.json()
150
+ job_id = payload.get('jobId')
129
151
  if job_id is None:
130
152
  raise Exception("Job ID is missing from event")
131
153
 
@@ -144,14 +166,22 @@ class AsyncInvocationTask(AsyncTask):
144
166
  JobManager.ensure_registry()
145
167
  ensure_started()
146
168
 
169
+ # After the registry and heartbeat are up, so neither of those
170
+ # long-lived processes is forked while this job's pipe is open.
171
+ capture = JobLogCapture.prepare(job_id, payload, job_log)
172
+
147
173
  loop = asyncio.get_running_loop()
148
174
  process = fork_context().Process(
149
- target=run_compute, args=(os.getpid(), _run_handle),
175
+ target=run_compute,
176
+ args=(os.getpid(), _run_handle,
177
+ capture.child_setup if capture else None),
150
178
  name=f'{COMPUTE_PROCESS_PREFIX}-{job_id}', daemon=False)
151
179
 
152
180
  try:
153
181
  process.start()
154
182
  except Exception as start_exception:
183
+ if capture is not None:
184
+ capture.failed_to_start()
155
185
  job_log.bind(event='compute_process_start_failed').exception(
156
186
  f'Could not start the compute process for job '
157
187
  f'{job_id}: {start_exception}')
@@ -161,7 +191,11 @@ class AsyncInvocationTask(AsyncTask):
161
191
  context={'jobId': job_id})
162
192
  raise
163
193
 
164
- self._watch_compute_process(loop, process, job_id, job_log)
194
+ if capture is not None:
195
+ capture.started()
196
+
197
+ self._watch_compute_process(loop, process, job_id, job_log,
198
+ capture)
165
199
 
166
200
  # Respond immediately so clients can poll GET /jobs/{job_id}
167
201
  return JSONResponse(status_code=200, content=Success(
@@ -173,13 +207,16 @@ class AsyncInvocationTask(AsyncTask):
173
207
  content=Error(exception).serialize(),
174
208
  headers=CLOSE_CONNECTION_HEADERS)
175
209
 
176
- def _watch_compute_process(self, loop, process, job_id, job_log) -> None:
210
+ def _watch_compute_process(self, loop, process, job_id, job_log,
211
+ capture=None) -> None:
177
212
  sentinel = process.sentinel
178
213
 
179
214
  def _on_process_exit():
180
215
  loop.remove_reader(sentinel)
181
216
  process.join()
182
217
  exit_code = process.exitcode
218
+ if capture is not None:
219
+ capture.process_exited(exit_code)
183
220
  if exit_code == 0:
184
221
  return
185
222
  self._report_compute_failure(loop, job_id, job_log, exit_code)
@@ -12,7 +12,7 @@ import time
12
12
  import requests
13
13
 
14
14
  from ...config.logging_config import logger
15
- from ...util.process_utils import release_inherited_server_sockets
15
+ from ...util.process_utils import release_inherited_fds
16
16
 
17
17
  REQUEST_TIMEOUT_SEC = 5.0
18
18
 
@@ -87,7 +87,7 @@ def _wait_for_next_beat(parent_pid: int, stop_event, interval: float) -> bool:
87
87
 
88
88
 
89
89
  def _heartbeat_loop(parent_pid: int, stop_event) -> None:
90
- release_inherited_server_sockets()
90
+ release_inherited_fds()
91
91
  while os.getppid() == parent_pid:
92
92
  try:
93
93
  beat_once()
@@ -13,7 +13,7 @@ from multiprocessing.managers import SyncManager
13
13
  from typing import Any, Callable, Dict, Iterable, Optional, Tuple
14
14
 
15
15
  from ...config.logging_config import logger
16
- from ...util.process_utils import release_inherited_server_sockets
16
+ from ...util.process_utils import release_inherited_fds
17
17
 
18
18
  SCHEDULER_CALLBACK_URL = 'scheduler_callback_url'
19
19
 
@@ -56,7 +56,7 @@ class JobManager:
56
56
  if cls._manager is not None:
57
57
  return
58
58
  mgr = SyncManager()
59
- mgr.start(initializer=release_inherited_server_sockets)
59
+ mgr.start(initializer=release_inherited_fds)
60
60
  cls._manager = mgr
61
61
  cls._jobs = mgr.dict() # type: ignore[assignment]
62
62
  cls._updates_queue = mgr.Queue() # type: ignore[assignment]
@@ -10,6 +10,8 @@ import requests
10
10
  from ..backend.job_manager import JobManager
11
11
  from ...config.log_context import phase
12
12
  from ...config.logging_config import job_logger
13
+ from ...joblog import child as job_log_child
14
+ from ...joblog.ingest import TOKEN_HEADER, WRITER_HEADER
13
15
  from ...data.response.job_response import JobResponse
14
16
  from ...enum.runtime_phase import RuntimePhase
15
17
  from ...util.http_utils import create_application_json_header, \
@@ -63,6 +65,17 @@ def _json_payload(payload: dict, logger) -> str:
63
65
  return json.dumps(_sanitize(payload), allow_nan=False, default=str)
64
66
 
65
67
 
68
+ def _with_log_writer(headers: dict) -> dict:
69
+ """Name the job log writer on the event PATCH (PQF-23860), so the backend
70
+ knows a writer whose open never got through. Only in a captured compute
71
+ process, i.e. only when the payload carried ``logIngest``."""
72
+ writer = job_log_child.current_writer()
73
+ if writer is None:
74
+ return headers
75
+ return {**headers, WRITER_HEADER: writer.writer_id,
76
+ TOKEN_HEADER: writer.token}
77
+
78
+
66
79
  def update_job_metadata(job_response: JobResponse, callback_url: str):
67
80
  # Helpers to improve readability and remove duplication
68
81
  def _log_http_result(tag: str, resp):
@@ -111,6 +124,10 @@ def update_job_metadata(job_response: JobResponse, callback_url: str):
111
124
  json=scheduler_payload)
112
125
  _log_http_result('scheduler', scheduler_response)
113
126
 
127
+ # Counted before anything can fail: a fetch process that tried to report
128
+ # something about the job keeps its log (see joblog.shipper).
129
+ job_log_child.count_callback()
130
+
114
131
  job_id = get_job_id_from_url(callback_url)
115
132
  logger = job_logger(job_id)
116
133
  logger.info(
@@ -129,10 +146,10 @@ def update_job_metadata(job_response: JobResponse, callback_url: str):
129
146
  # for exactly this and had no place that opened it.
130
147
  with phase(RuntimePhase.CALLBACK):
131
148
  try:
132
- request_headers = create_application_json_header(
149
+ request_headers = _with_log_writer(create_application_json_header(
133
150
  token=job_response.user_token,
134
151
  project_header=job_response.project_header,
135
- workspace_header=job_response.workspace_header)
152
+ workspace_header=job_response.workspace_header))
136
153
 
137
154
  # data= rather than json=: the body goes through _json_payload so no
138
155
  # provider object can kill this callback. Content-Type is already
@@ -135,11 +135,11 @@ def _inject_job_context(record) -> None:
135
135
  def _prepare_record(record) -> bool:
136
136
  """loguru filter: fill in context, mask the message, pre-format the traceback.
137
137
 
138
- The filter runs in the process that logged, BEFORE the record is put on the
139
- ``enqueue=True`` queue. This is the only place that can still see the real
140
- traceback object -- once through the queue, the traceback is not picklable so
141
- it is replaced with None and ``traceback.format_exception()`` inside the sink
142
- can only produce the last line.
138
+ The filter runs in the process that logged, before any sink. The traceback is
139
+ formatted here, so a sink never depends on the traceback object itself: it
140
+ would not survive a pickling queue (``enqueue=True``, which the sinks no
141
+ longer use, see ``configure_logging``), where it is replaced with None and
142
+ ``traceback.format_exception()`` can only produce the last line.
143
143
 
144
144
  Returns True to keep the record.
145
145
  """
@@ -296,6 +296,14 @@ def configure_logging(force: bool = False) -> None:
296
296
 
297
297
  logger.remove()
298
298
 
299
+ # enqueue=False is MANDATORY: this process forks (a compute process per job,
300
+ # the heartbeat, the SyncManager). With enqueue=True, loguru's at-fork hook
301
+ # takes the handler locks in WeakSet order; when it holds the queue lock and
302
+ # waits for the handler lock while another thread holds that lock, blocked on
303
+ # a full queue that only the writer thread -- itself waiting for the queue
304
+ # lock -- can drain, the fork never returns and the server hangs. Writing
305
+ # directly leaves no writer thread, so no cycle (~1 hang in 4 runs of
306
+ # test_forking_while_the_parent_logs_never_hangs before, none after).
299
307
  if LOG_FORMAT in ('text', 'both'):
300
308
  # diagnose=False is MANDATORY: loguru's diagnose prints local variable
301
309
  # values inside the traceback as `└ 'value'`. There is no key name, so
@@ -304,18 +312,45 @@ def configure_logging(force: bool = False) -> None:
304
312
  # verbatim. backtrace=True stays: it widens the call chain but prints no
305
313
  # values.
306
314
  logger.add(sink=sys.stderr, format=__custom_format, level=LOG_LEVEL,
307
- colorize=True, filter=_prepare_record, enqueue=True,
315
+ colorize=True, filter=_prepare_record, enqueue=False,
308
316
  backtrace=True, diagnose=False)
309
317
 
310
318
  if LOG_FORMAT in ('json', 'both'):
311
319
  logger.add(sink=_json_sink, level=LOG_LEVEL, filter=_prepare_record,
312
- enqueue=True, backtrace=False, diagnose=False)
320
+ enqueue=False, backtrace=False, diagnose=False)
313
321
 
314
322
  install_stdlib_intercept()
315
323
 
316
324
  _CONFIGURED = True
317
325
 
318
326
 
327
+ def configure_child_logging() -> None:
328
+ """Re-create the sinks in a captured compute process (PQF-23860).
329
+
330
+ The inherited sinks write through the parent's ``sys.stderr`` object; the
331
+ child replaced ``sys.stderr`` with a fresh object on its log pipe, so the
332
+ sinks are rebuilt on that one. ``remove()`` is safe
333
+ after fork: loguru only stops handlers its own process started.
334
+
335
+ ``colorize=False``: the parent recognises this job's lines by their
336
+ ``[ConsoleJobLog][<jobId>]`` start, which ANSI codes would hide.
337
+ """
338
+ global _CONFIGURED
339
+
340
+ logger.remove()
341
+
342
+ if LOG_FORMAT in ('text', 'both'):
343
+ logger.add(sink=sys.stderr, format=__custom_format, level=LOG_LEVEL,
344
+ colorize=False, filter=_prepare_record, enqueue=False,
345
+ backtrace=True, diagnose=False)
346
+
347
+ if LOG_FORMAT in ('json', 'both'):
348
+ logger.add(sink=_json_sink, level=LOG_LEVEL, filter=_prepare_record,
349
+ enqueue=False, backtrace=False, diagnose=False)
350
+
351
+ _CONFIGURED = True
352
+
353
+
319
354
  def job_logger(job_id: str = None):
320
355
  """Logger for one job. The old signature is kept so the 12 provider libs and
321
356
  the templates need no import changes.
@@ -0,0 +1,3 @@
1
+ # Quapp Platform Project
2
+ # __init__.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
@@ -0,0 +1,118 @@
1
+ # Quapp Platform Project
2
+ # capture.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
4
+
5
+ """Live job log capture for one compute process (PQF-23860, H7).
6
+
7
+ ``AsyncInvocationTask`` uses it around the fork::
8
+
9
+ capture = JobLogCapture.prepare(job_id, payload) # None: old behaviour
10
+ process = Process(target=run_compute,
11
+ args=(..., capture.child_setup if capture else None))
12
+ process.start() # on failure: capture.failed_to_start()
13
+ capture.started() # parent closes its write end, threads start
14
+ ...
15
+ capture.process_exited(exit_code)
16
+
17
+ Only a payload with a usable ``logIngest`` block is captured. Without one the
18
+ runtime behaves exactly as before: no pipe, no prefixing, no network. That keeps
19
+ a newer quapp-common harmless where the backend does not send ``logIngest``.
20
+ """
21
+
22
+ import atexit
23
+ import multiprocessing
24
+ import threading
25
+ import time
26
+ import uuid
27
+ from typing import Optional
28
+
29
+ from . import child, pipes
30
+ from .ingest import IngestClient, LogIngest
31
+ from .shipper import JobLogShipper
32
+
33
+ PROVIDER_JOB_ID = 'providerJobId'
34
+ SHUTDOWN_GRACE_SEC = 8.0
35
+
36
+ _active = set()
37
+ _active_lock = threading.Lock()
38
+ _atexit_registered = False
39
+
40
+
41
+ class JobLogCapture:
42
+
43
+ def __init__(self, job_id: str, ingest: LogIngest, fetch: bool,
44
+ logger=None):
45
+ self.job_id = job_id
46
+ self.writer_id = str(uuid.uuid4())
47
+ self.fetch = fetch
48
+ self._ingest = ingest
49
+ self._logger = logger
50
+ self._callbacks = multiprocessing.get_context('fork').RawValue('i', 0)
51
+ self._read_fd, self._write_fd = pipes.open_pipe(self.writer_id)
52
+ self._shipper: Optional[JobLogShipper] = None
53
+
54
+ @staticmethod
55
+ def prepare(job_id: str, payload, logger=None) -> Optional['JobLogCapture']:
56
+ ingest = LogIngest.from_payload(payload)
57
+ if ingest is None or not job_id:
58
+ return None
59
+ fetch = isinstance(payload, dict) and payload.get(
60
+ PROVIDER_JOB_ID) is not None
61
+ try:
62
+ return JobLogCapture(job_id, ingest, fetch, logger)
63
+ except Exception as exception:
64
+ if logger is not None:
65
+ logger.warning(f'Live job log is off for job {job_id}: could '
66
+ f'not set up the pipe ({exception})')
67
+ return None
68
+
69
+ def child_setup(self) -> None:
70
+ """Runs in the compute process, before the handler is built."""
71
+ child.attach(self._write_fd, self.writer_id, self._ingest.token,
72
+ self._callbacks)
73
+
74
+ def started(self) -> None:
75
+ """Runs in the server after the fork succeeded."""
76
+ pipes.close_fd(self._write_fd)
77
+ self._shipper = JobLogShipper(self.job_id, self.writer_id,
78
+ IngestClient(self._ingest,
79
+ self.writer_id),
80
+ self._read_fd, fetch=self.fetch,
81
+ callbacks=self._callbacks,
82
+ logger=self._logger, on_done=_untrack)
83
+ _track(self._shipper)
84
+ self._shipper.start()
85
+
86
+ def failed_to_start(self) -> None:
87
+ pipes.close_fd(self._write_fd)
88
+ pipes.close_fd(self._read_fd)
89
+
90
+ def process_exited(self, exit_code: Optional[int]) -> None:
91
+ if self._shipper is not None:
92
+ self._shipper.process_exited(exit_code)
93
+
94
+
95
+ def _track(shipper: JobLogShipper) -> None:
96
+ global _atexit_registered
97
+ with _active_lock:
98
+ _active.add(shipper)
99
+ if not _atexit_registered:
100
+ atexit.register(_shutdown_all)
101
+ _atexit_registered = True
102
+
103
+
104
+ def _untrack(shipper: JobLogShipper) -> None:
105
+ with _active_lock:
106
+ _active.discard(shipper)
107
+
108
+
109
+ def _shutdown_all() -> None:
110
+ """The server is exiting (pod deleted): every live writer sends what it has
111
+ and closes as abandoned, within the pod's grace period."""
112
+ with _active_lock:
113
+ shippers = list(_active)
114
+ for shipper in shippers:
115
+ shipper.request_shutdown()
116
+ deadline = time.monotonic() + SHUTDOWN_GRACE_SEC
117
+ for shipper in shippers:
118
+ shipper.join_sender(max(deadline - time.monotonic(), 0.0))