yql_facade.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. #include "yql_facade.h"
  2. #include <yql/essentials/core/yql_execution.h>
  3. #include <yql/essentials/core/yql_expr_csee.h>
  4. #include <yql/essentials/core/yql_expr_optimize.h>
  5. #include <yql/essentials/core/yql_expr_type_annotation.h>
  6. #include <yql/essentials/core/yql_opt_rewrite_io.h>
  7. #include <yql/essentials/core/yql_opt_proposed_by_data.h>
  8. #include <yql/essentials/core/yql_gc_transformer.h>
  9. #include <yql/essentials/core/type_ann/type_ann_expr.h>
  10. #include <yql/essentials/core/services/yql_plan.h>
  11. #include <yql/essentials/core/services/yql_eval_params.h>
  12. #include <yql/essentials/utils/log/context.h>
  13. #include <yql/essentials/utils/log/profile.h>
  14. #include <yql/essentials/utils/limiting_allocator.h>
  15. #include <yql/essentials/core/services/yql_out_transformers.h>
  16. #include <yql/essentials/core/extract_predicate/extract_predicate_dbg.h>
  17. #include <yql/essentials/providers/common/provider/yql_provider_names.h>
  18. #include <yql/essentials/providers/common/provider/yql_provider.h>
  19. #include <yql/essentials/providers/common/udf_resolve/yql_simple_udf_resolver.h>
  20. #include <yql/essentials/providers/common/udf_resolve/yql_outproc_udf_resolver.h>
  21. #include <yql/essentials/providers/common/udf_resolve/yql_udf_resolver_with_index.h>
  22. #include <yql/essentials/providers/common/arrow_resolve/yql_simple_arrow_resolver.h>
  23. #include <yql/essentials/providers/common/config/yql_setting.h>
  24. #include <yql/essentials/core/qplayer/udf_resolver/yql_qplayer_udf_resolver.h>
  25. #include <library/cpp/yson/node/node_io.h>
  26. #include <library/cpp/deprecated/split/split_iterator.h>
  27. #include <library/cpp/yson/writer.h>
  28. #include <library/cpp/string_utils/base64/base64.h>
  29. #include <util/stream/file.h>
  30. #include <util/stream/null.h>
  31. #include <util/string/join.h>
  32. #include <util/string/split.h>
  33. #include <util/generic/guid.h>
  34. #include <util/system/rusage.h>
  35. #include <util/generic/yexception.h>
  36. using namespace NThreading;
  37. namespace NYql {
  38. namespace {
  39. const size_t DEFAULT_AST_BUF_SIZE = 1024;
  40. const size_t DEFAULT_PLAN_BUF_SIZE = 1024;
  41. const TString FacadeComponent = "Facade";
  42. const TString SourceCodeLabel = "SourceCode";
  43. const TString GatewaysLabel = "Gateways";
  44. const TString ParametersLabel = "Parameters";
  45. const TString TranslationLabel = "Translation";
  46. const TString StaticUserFilesLabel = "UserFiles";
  47. const TString DynamicUserFilesLabel = "DynamicUserFiles";
  48. const TString StaticCredentialsLabel = "Credentials";
  49. const TString DynamicCredentialsLabel = "DynamicCredentials";
  50. class TUrlLoader : public IUrlLoader {
  51. public:
  52. TUrlLoader(TFileStoragePtr storage)
  53. : Storage_(storage)
  54. {}
  55. TString Load(const TString& url, const TString& token) override {
  56. auto file = Storage_->PutUrl(url, token);
  57. return TFileInput(file->GetPath()).ReadAll();
  58. }
  59. private:
  60. TFileStoragePtr Storage_;
  61. };
  62. template <typename... Params1, typename... Params2>
  63. TProgram::TStatus SyncExecution(
  64. TProgram* program,
  65. TProgram::TFutureStatus (TProgram::*method)(Params1...),
  66. Params2&&... params) {
  67. TProgram::TFutureStatus future =
  68. (program->*method)(std::forward<Params2>(params)...);
  69. YQL_ENSURE(future.Initialized());
  70. future.Wait();
  71. HandleFutureException(future);
  72. TProgram::TStatus status = future.GetValue();
  73. while (status == TProgram::TStatus::Async) {
  74. auto continueFuture = program->ContinueAsync();
  75. continueFuture.Wait();
  76. HandleFutureException(continueFuture);
  77. status = continueFuture.GetValue();
  78. }
  79. if (status == TProgram::TStatus::Error) {
  80. program->Print(program->ExprStream(), program->PlanStream());
  81. }
  82. return status;
  83. }
  84. std::function<TString(const TString&, const TString&)> BuildDefaultTokenResolver(TCredentials::TPtr credentials) {
  85. return [credentials](const TString& /*url*/, const TString& alias) -> TString {
  86. if (alias) {
  87. if (auto cred = credentials->FindCredential(TString("default_").append(alias))) {
  88. return cred->Content;
  89. }
  90. }
  91. return {};
  92. };
  93. }
  94. std::function<TString(const TString&, const TString&)> BuildCompositeTokenResolver(TVector<std::function<TString(const TString&, const TString&)>>&& children) {
  95. if (children.empty()) {
  96. return {};
  97. }
  98. if (children.size() == 1) {
  99. return std::move(children[0]);
  100. }
  101. return [children = std::move(children)](const TString& url, const TString& alias) -> TString {
  102. for (auto& c : children) {
  103. if (auto r = c(url, alias)) {
  104. return r;
  105. }
  106. }
  107. return {};
  108. };
  109. }
  110. } // namspace
  111. ///////////////////////////////////////////////////////////////////////////////
  112. // TProgramFactory
  113. ///////////////////////////////////////////////////////////////////////////////
  114. TProgramFactory::TProgramFactory(
  115. bool useRepeatableRandomAndTimeProviders,
  116. const NKikimr::NMiniKQL::IFunctionRegistry* functionRegistry,
  117. ui64 nextUniqueId,
  118. const TVector<TDataProviderInitializer>& dataProvidersInit,
  119. const TString& runner)
  120. : UseRepeatableRandomAndTimeProviders_(useRepeatableRandomAndTimeProviders)
  121. , FunctionRegistry_(functionRegistry)
  122. , NextUniqueId_(nextUniqueId)
  123. , DataProvidersInit_(dataProvidersInit)
  124. , Credentials_(MakeIntrusive<TCredentials>())
  125. , GatewaysConfig_(nullptr)
  126. , Runner_(runner)
  127. , ArrowResolver_(MakeSimpleArrowResolver(*functionRegistry))
  128. {
  129. }
  130. void TProgramFactory::UnrepeatableRandom() {
  131. UseUnrepeatableRandom = true;
  132. }
  133. void TProgramFactory::EnableRangeComputeFor() {
  134. EnableRangeComputeFor_ = true;
  135. }
  136. void TProgramFactory::AddUserDataTable(const TUserDataTable& userDataTable) {
  137. for (const auto& p : userDataTable) {
  138. if (!UserDataTable_.emplace(p).second) {
  139. ythrow yexception() << "UserDataTable already has user data block with key " << p.first;
  140. }
  141. }
  142. }
  143. void TProgramFactory::SetCredentials(TCredentials::TPtr credentials) {
  144. Credentials_ = std::move(credentials);
  145. }
  146. void TProgramFactory::SetGatewaysConfig(const TGatewaysConfig* gatewaysConfig) {
  147. GatewaysConfig_ = gatewaysConfig;
  148. }
  149. void TProgramFactory::SetModules(IModuleResolver::TPtr modules) {
  150. Modules_ = modules;
  151. }
  152. void TProgramFactory::SetUdfResolver(IUdfResolver::TPtr udfResolver) {
  153. UdfResolver_ = udfResolver;
  154. }
  155. void TProgramFactory::SetUdfIndex(TUdfIndex::TPtr udfIndex, TUdfIndexPackageSet::TPtr udfIndexPackageSet) {
  156. UdfIndex_ = std::move(udfIndex);
  157. UdfIndexPackageSet_ = std::move(udfIndexPackageSet);
  158. }
  159. void TProgramFactory::SetFileStorage(TFileStoragePtr fileStorage) {
  160. FileStorage_ = std::move(fileStorage);
  161. }
  162. void TProgramFactory::SetUrlPreprocessing(IUrlPreprocessing::TPtr urlPreprocessing) {
  163. UrlPreprocessing_ = std::move(urlPreprocessing);
  164. }
  165. void TProgramFactory::SetArrowResolver(IArrowResolver::TPtr arrowResolver) {
  166. ArrowResolver_ = arrowResolver;
  167. }
  168. void TProgramFactory::SetUrlListerManager(IUrlListerManagerPtr urlListerManager) {
  169. UrlListerManager_ = std::move(urlListerManager);
  170. }
  171. TProgramPtr TProgramFactory::Create(
  172. const TFile& file,
  173. const TString& sessionId,
  174. const TQContext& qContext)
  175. {
  176. TString sourceCode = TFileInput(file).ReadAll();
  177. return Create(file.GetName(), sourceCode, sessionId, EHiddenMode::Disable, qContext);
  178. }
  179. TProgramPtr TProgramFactory::Create(
  180. const TString& filename,
  181. const TString& sourceCode,
  182. const TString& sessionId,
  183. EHiddenMode hiddenMode,
  184. const TQContext& qContext)
  185. {
  186. auto randomProvider = UseRepeatableRandomAndTimeProviders_ && !UseUnrepeatableRandom && hiddenMode == EHiddenMode::Disable ?
  187. CreateDeterministicRandomProvider(1) : CreateDefaultRandomProvider();
  188. auto timeProvider = UseRepeatableRandomAndTimeProviders_ ?
  189. CreateDeterministicTimeProvider(10000000) : CreateDefaultTimeProvider();
  190. TUdfIndex::TPtr udfIndex = UdfIndex_ ? UdfIndex_->Clone() : nullptr;
  191. TUdfIndexPackageSet::TPtr udfIndexPackageSet = (UdfIndexPackageSet_ && hiddenMode == EHiddenMode::Disable) ? UdfIndexPackageSet_->Clone() : nullptr;
  192. IModuleResolver::TPtr moduleResolver = Modules_ ? Modules_->CreateMutableChild() : nullptr;
  193. IUrlListerManagerPtr urlListerManager = UrlListerManager_ ? UrlListerManager_->Clone() : nullptr;
  194. auto udfResolver = udfIndex ? NCommon::CreateUdfResolverWithIndex(udfIndex, UdfResolver_, FileStorage_) : UdfResolver_;
  195. // make UserDataTable_ copy here
  196. return new TProgram(FunctionRegistry_, randomProvider, timeProvider, NextUniqueId_, DataProvidersInit_,
  197. UserDataTable_, Credentials_, moduleResolver, urlListerManager,
  198. udfResolver, udfIndex, udfIndexPackageSet, FileStorage_, UrlPreprocessing_,
  199. GatewaysConfig_, filename, sourceCode, sessionId, Runner_, EnableRangeComputeFor_, ArrowResolver_, hiddenMode,
  200. qContext);
  201. }
  202. ///////////////////////////////////////////////////////////////////////////////
  203. // TProgram
  204. ///////////////////////////////////////////////////////////////////////////////
  205. TProgram::TProgram(
  206. const NKikimr::NMiniKQL::IFunctionRegistry* functionRegistry,
  207. const TIntrusivePtr<IRandomProvider> randomProvider,
  208. const TIntrusivePtr<ITimeProvider> timeProvider,
  209. ui64 nextUniqueId,
  210. const TVector<TDataProviderInitializer>& dataProvidersInit,
  211. const TUserDataTable& userDataTable,
  212. const TCredentials::TPtr& credentials,
  213. const IModuleResolver::TPtr& modules,
  214. const IUrlListerManagerPtr& urlListerManager,
  215. const IUdfResolver::TPtr& udfResolver,
  216. const TUdfIndex::TPtr& udfIndex,
  217. const TUdfIndexPackageSet::TPtr& udfIndexPackageSet,
  218. const TFileStoragePtr& fileStorage,
  219. const IUrlPreprocessing::TPtr& urlPreprocessing,
  220. const TGatewaysConfig* gatewaysConfig,
  221. const TString& filename,
  222. const TString& sourceCode,
  223. const TString& sessionId,
  224. const TString& runner,
  225. bool enableRangeComputeFor,
  226. const IArrowResolver::TPtr& arrowResolver,
  227. EHiddenMode hiddenMode,
  228. const TQContext& qContext
  229. )
  230. : FunctionRegistry_(functionRegistry)
  231. , RandomProvider_(randomProvider)
  232. , TimeProvider_(timeProvider)
  233. , NextUniqueId_(nextUniqueId)
  234. , AstRoot_(nullptr)
  235. , Modules_(modules)
  236. , DataProvidersInit_(dataProvidersInit)
  237. , Credentials_(MakeIntrusive<NYql::TCredentials>(*credentials))
  238. , UrlListerManager_(urlListerManager)
  239. , UdfResolver_(udfResolver)
  240. , UdfIndex_(udfIndex)
  241. , UdfIndexPackageSet_(udfIndexPackageSet)
  242. , FileStorage_(fileStorage)
  243. , SavedUserDataTable_(userDataTable)
  244. , GatewaysConfig_(gatewaysConfig)
  245. , Filename_(filename)
  246. , SourceCode_(sourceCode)
  247. , SourceSyntax_(ESourceSyntax::Unknown)
  248. , SyntaxVersion_(0)
  249. , ExprRoot_(nullptr)
  250. , SessionId_(sessionId)
  251. , ResultType_(IDataProvider::EResultFormat::Yson)
  252. , ResultFormat_(NYson::EYsonFormat::Binary)
  253. , OutputFormat_(NYson::EYsonFormat::Pretty)
  254. , EnableRangeComputeFor_(enableRangeComputeFor)
  255. , ArrowResolver_(arrowResolver)
  256. , HiddenMode_(hiddenMode)
  257. , QContext_(qContext)
  258. {
  259. if (SessionId_.empty()) {
  260. SessionId_ = CreateGuidAsString();
  261. }
  262. if (QContext_.CanWrite()) {
  263. NYT::TNode credListNode = NYT::TNode::CreateList();
  264. Credentials_->ForEach([&](const TString name, const TCredential& cred) {
  265. credListNode.Add(NYT::TNode()
  266. ("Name", name)
  267. ("Category", cred.Category)
  268. ("Subcategory", cred.Subcategory));
  269. });
  270. auto credList = NYT::NodeToYsonString(credListNode, NYT::NYson::EYsonFormat::Binary);
  271. QContext_.GetWriter()->Put({FacadeComponent, StaticCredentialsLabel}, credList).GetValueSync();
  272. } else if (QContext_.CanRead()) {
  273. Credentials_ = MakeIntrusive<TCredentials>();
  274. Credentials_->SetUserCredentials({
  275. .OauthToken = "REPLAY_OAUTH",
  276. .BlackboxSessionIdCookie = "REPLAY_SESSIONID"
  277. });
  278. for (const auto& label : {StaticCredentialsLabel, DynamicCredentialsLabel}) {
  279. auto item = QContext_.GetReader()->Get({FacadeComponent, label}).GetValueSync();
  280. if (item) {
  281. auto node = NYT::NodeFromYsonString(item->Value);
  282. for (const auto& c : node.AsList()) {
  283. Credentials_->AddCredential(c["Name"].AsString(), TCredential(
  284. c["Category"].AsString(),c["Subcategory"].AsString(),"REPLAY"));
  285. }
  286. }
  287. }
  288. }
  289. if (QContext_.CanWrite() && !SavedUserDataTable_.empty()) {
  290. NYT::TNode userFilesNode = NYT::TNode::CreateList();
  291. for (const auto& p : SavedUserDataTable_) {
  292. userFilesNode.Add(p.first.Alias());
  293. }
  294. auto userFiles = NYT::NodeToYsonString(userFilesNode, NYT::NYson::EYsonFormat::Binary);
  295. QContext_.GetWriter()->Put({FacadeComponent, StaticUserFilesLabel}, userFiles).GetValueSync();
  296. } else if (QContext_.CanRead()) {
  297. SavedUserDataTable_.clear();
  298. for (const auto& label : {StaticUserFilesLabel, DynamicUserFilesLabel}) {
  299. auto item = QContext_.GetReader()->Get({FacadeComponent, label}).GetValueSync();
  300. if (item) {
  301. auto node = NYT::NodeFromYsonString(item->Value);
  302. for (const auto& alias : node.AsList()) {
  303. TUserDataBlock block;
  304. block.Type = EUserDataType::RAW_INLINE_DATA;
  305. YQL_ENSURE(SavedUserDataTable_.emplace(TUserDataKey::File(alias.AsString()), block).second);
  306. }
  307. }
  308. }
  309. }
  310. UserDataStorage_ = MakeIntrusive<TUserDataStorage>(fileStorage, SavedUserDataTable_, udfResolver, udfIndex);
  311. if (auto modules = dynamic_cast<TModuleResolver*>(Modules_.get())) {
  312. modules->AttachUserData(UserDataStorage_);
  313. modules->SetUrlLoader(new TUrlLoader(FileStorage_));
  314. modules->SetCredentials(Credentials_);
  315. if (QContext_) {
  316. modules->SetQContext(QContext_);
  317. }
  318. }
  319. if (UrlListerManager_) {
  320. UrlListerManager_->SetCredentials(Credentials_);
  321. UrlListerManager_->SetUrlPreprocessing(urlPreprocessing);
  322. }
  323. OperationOptions_.Runner = runner;
  324. UserDataStorage_->SetUrlPreprocessor(urlPreprocessing);
  325. if (QContext_) {
  326. UdfResolver_ = NCommon::WrapUdfResolverWithQContext(UdfResolver_, QContext_);
  327. if (QContext_.CanRead()) {
  328. auto item = QContext_.GetReader()->Get({FacadeComponent, GatewaysLabel}).GetValueSync();
  329. if (item) {
  330. YQL_ENSURE(LoadedGatewaysConfig_.ParseFromString(item->Value));
  331. GatewaysConfig_ = &LoadedGatewaysConfig_;
  332. }
  333. } else if (QContext_.CanWrite() && GatewaysConfig_) {
  334. TGatewaysConfig cleaned;
  335. if (GatewaysConfig_->HasYt()) {
  336. cleaned.MutableYt()->CopyFrom(GatewaysConfig_->GetYt());
  337. }
  338. if (GatewaysConfig_->HasFs()) {
  339. cleaned.MutableFs()->CopyFrom(GatewaysConfig_->GetFs());
  340. }
  341. if (GatewaysConfig_->HasYqlCore()) {
  342. cleaned.MutableYqlCore()->CopyFrom(GatewaysConfig_->GetYqlCore());
  343. }
  344. if (GatewaysConfig_->HasSqlCore()) {
  345. cleaned.MutableSqlCore()->CopyFrom(GatewaysConfig_->GetSqlCore());
  346. }
  347. if (GatewaysConfig_->HasDq()) {
  348. cleaned.MutableDq()->CopyFrom(GatewaysConfig_->GetDq());
  349. }
  350. auto data = cleaned.SerializeAsString();
  351. QContext_.GetWriter()->Put({FacadeComponent, GatewaysLabel}, data).GetValueSync();
  352. }
  353. if (QContext_.CanRead()) {
  354. auto item = QContext_.GetReader()->Get({FacadeComponent, ParametersLabel}).GetValueSync();
  355. if (item) {
  356. SetParametersYson(item->Value);
  357. }
  358. }
  359. }
  360. }
  361. TProgram::~TProgram() {
  362. try {
  363. CloseLastSession().GetValueSync();
  364. // stop all non complete execution before deleting TExprCtx
  365. with_lock (DataProvidersLock_) {
  366. DataProviders_.clear();
  367. }
  368. } catch (...) {
  369. Cerr << CurrentExceptionMessage() << Endl;
  370. }
  371. }
  372. void TProgram::ConfigureYsonResultFormat(NYson::EYsonFormat format) {
  373. ResultFormat_ = format;
  374. OutputFormat_ = format;
  375. }
  376. void TProgram::SetValidateOptions(NUdf::EValidateMode validateMode) {
  377. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  378. ValidateMode_ = validateMode;
  379. }
  380. void TProgram::SetDisableNativeUdfSupport(bool disable) {
  381. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  382. DisableNativeUdfSupport_ = disable;
  383. }
  384. void TProgram::SetUseTableMetaFromGraph(bool use) {
  385. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  386. UseTableMetaFromGraph_ = use;
  387. }
  388. TTypeAnnotationContextPtr TProgram::GetAnnotationContext() const {
  389. Y_ENSURE(TypeCtx_, "TypeCtx_ is not created");
  390. return TypeCtx_;
  391. }
  392. TTypeAnnotationContextPtr TProgram::ProvideAnnotationContext(const TString& username) {
  393. if (!TypeCtx_) {
  394. TypeCtx_ = BuildTypeAnnotationContext(username);
  395. TypeCtx_->OperationOptions = OperationOptions_;
  396. TypeCtx_->ValidateMode = ValidateMode_;
  397. TypeCtx_->DisableNativeUdfSupport = DisableNativeUdfSupport_;
  398. TypeCtx_->UseTableMetaFromGraph = UseTableMetaFromGraph_;
  399. }
  400. return TypeCtx_;
  401. }
  402. IPlanBuilder& TProgram::GetPlanBuilder() {
  403. if (!PlanBuilder_) {
  404. PlanBuilder_ = CreatePlanBuilder(*GetAnnotationContext());
  405. }
  406. return *PlanBuilder_;
  407. }
  408. void TProgram::SetParametersYson(const TString& parameters) {
  409. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  410. auto node = NYT::NodeFromYsonString(parameters);
  411. YQL_ENSURE(node.IsMap());
  412. for (const auto& x : node.AsMap()) {
  413. YQL_ENSURE(x.second.IsMap());
  414. YQL_ENSURE(x.second.HasKey("Data"));
  415. YQL_ENSURE(x.second.Size() == 1);
  416. }
  417. OperationOptions_.ParametersYson = node;
  418. if (auto modules = dynamic_cast<TModuleResolver*>(Modules_.get())) {
  419. modules->SetParameters(node);
  420. }
  421. if (UrlListerManager_) {
  422. UrlListerManager_->SetParameters(node);
  423. }
  424. if (QContext_.CanWrite()) {
  425. QContext_.GetWriter()->Put({FacadeComponent, ParametersLabel}, parameters).GetValueSync();
  426. }
  427. }
  428. bool TProgram::ExtractQueryParametersMetadata() {
  429. auto& types = *GetAnnotationContext();
  430. NYT::TNode params = NYT::TNode::CreateMap();
  431. Y_ENSURE(ExprCtx_);
  432. if (!ExtractParametersMetaAsYson(ExprRoot_, types, *ExprCtx_, params)) {
  433. return false;
  434. }
  435. ExtractedQueryParametersMetadataYson_ = NYT::NodeToYsonString(params, ResultFormat_);
  436. return true;
  437. }
  438. bool TProgram::FillParseResult(NYql::TAstParseResult&& astRes, NYql::TWarningRules* warningRules) {
  439. if (!astRes.Issues.Empty()) {
  440. if (!ExprCtx_) {
  441. ExprCtx_.Reset(new TExprContext(NextUniqueId_));
  442. }
  443. auto& iManager = ExprCtx_->IssueManager;
  444. if (warningRules) {
  445. for (auto warningRule: *warningRules) {
  446. iManager.AddWarningRule(warningRule);
  447. }
  448. }
  449. iManager.AddScope([this]() {
  450. TIssuePtr issueHolder = new TIssue();
  451. issueHolder->SetMessage(TStringBuilder() << "Parse " << SourceSyntax_);
  452. issueHolder->Severity = TSeverityIds::S_INFO;
  453. return issueHolder;
  454. });
  455. for (auto issue: astRes.Issues) {
  456. iManager.RaiseWarning(issue);
  457. }
  458. iManager.LeaveScope();
  459. }
  460. if (!astRes.IsOk()) {
  461. return false;
  462. }
  463. AstRoot_ = astRes.Root;
  464. AstPool_ = std::move(astRes.Pool);
  465. return true;
  466. }
  467. TString TProgram::GetSessionId() const {
  468. with_lock(SessionIdLock_) {
  469. return SessionId_;
  470. }
  471. }
  472. void TProgram::AddCredentials(const TVector<std::pair<TString, TCredential>>& credentials) {
  473. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  474. if (QContext_.CanWrite()) {
  475. NYT::TNode credListNode = NYT::TNode::CreateList();
  476. for (const auto& c : credentials) {
  477. credListNode.Add(NYT::TNode()
  478. ("Name", c.first)
  479. ("Category", c.second.Category)
  480. ("Subcategory", c.second.Subcategory));
  481. }
  482. auto credList = NYT::NodeToYsonString(credListNode, NYT::NYson::EYsonFormat::Binary);
  483. QContext_.GetWriter()->Put({FacadeComponent, DynamicCredentialsLabel}, credList).GetValueSync();
  484. }
  485. for (const auto& credential : credentials) {
  486. Credentials_->AddCredential(credential.first, credential.second);
  487. }
  488. if (auto modules = dynamic_cast<TModuleResolver*>(Modules_.get())) {
  489. modules->SetCredentials(Credentials_);
  490. }
  491. if (UrlListerManager_) {
  492. UrlListerManager_->SetCredentials(Credentials_);
  493. }
  494. }
  495. void TProgram::ClearCredentials() {
  496. Y_ENSURE(!TypeCtx_, "TypeCtx_ already created");
  497. Credentials_ = MakeIntrusive<TCredentials>();
  498. if (auto modules = dynamic_cast<TModuleResolver*>(Modules_.get())) {
  499. modules->SetCredentials(Credentials_);
  500. }
  501. if (UrlListerManager_) {
  502. UrlListerManager_->SetCredentials(Credentials_);
  503. }
  504. }
  505. void TProgram::AddUserDataTable(const TUserDataTable& userDataTable) {
  506. for (const auto& p : userDataTable) {
  507. if (!SavedUserDataTable_.emplace(p).second) {
  508. ythrow yexception() << "UserDataTable already has user data block with key " << p.first;
  509. }
  510. UserDataStorage_->AddUserDataBlock(p.first, p.second);
  511. }
  512. if (QContext_.CanWrite()) {
  513. NYT::TNode userFilesNode;
  514. for (const auto& p : userDataTable) {
  515. userFilesNode.Add(p.first.Alias());
  516. }
  517. auto userFiles = NYT::NodeToYsonString(userFilesNode, NYT::NYson::EYsonFormat::Binary);
  518. QContext_.GetWriter()->Put({FacadeComponent, DynamicUserFilesLabel}, userFiles).GetValueSync();
  519. }
  520. }
  521. void TProgram::HandleSourceCode(TString& sourceCode) {
  522. if (QContext_.CanWrite()) {
  523. QContext_.GetWriter()->Put({FacadeComponent, SourceCodeLabel}, sourceCode).GetValueSync();
  524. } else if (QContext_.CanRead()) {
  525. auto loaded = QContext_.GetReader()->Get({FacadeComponent, SourceCodeLabel}).GetValueSync();
  526. Y_ENSURE(loaded.Defined(), "No source code");
  527. sourceCode = loaded->Value;
  528. }
  529. }
  530. namespace {
  531. THashSet<TString> ExtractSqlFlags(const NYT::TNode& dataNode) {
  532. THashSet<TString> result;
  533. for (const auto& f : dataNode["SqlFlags"].AsList()) {
  534. result.insert(f.AsString());
  535. }
  536. return result;
  537. }
  538. } // namespace
  539. void UpdateSqlFlagsFromQContext(const TQContext& qContext, THashSet<TString>& flags) {
  540. if (qContext.CanRead()) {
  541. auto loaded = qContext.GetReader()->Get({FacadeComponent, TranslationLabel}).GetValueSync();
  542. if (!loaded) {
  543. return;
  544. }
  545. auto dataNode = NYT::NodeFromYsonString(loaded->Value);
  546. flags = ExtractSqlFlags(dataNode);
  547. }
  548. }
  549. void TProgram::HandleTranslationSettings(NSQLTranslation::TTranslationSettings& loadedSettings,
  550. const NSQLTranslation::TTranslationSettings*& currentSettings)
  551. {
  552. if (QContext_.CanWrite()) {
  553. auto clusterMappingsNode = NYT::TNode::CreateMap();
  554. for (const auto& c : currentSettings->ClusterMapping) {
  555. clusterMappingsNode(c.first, c.second);
  556. }
  557. auto sqlFlagsNode = NYT::TNode::CreateList();
  558. for (const auto& f : currentSettings->Flags) {
  559. sqlFlagsNode.Add(f);
  560. }
  561. auto dataNode = NYT::TNode()
  562. ("ClusterMapping", clusterMappingsNode)
  563. ("V0Behavior", ui64(currentSettings->V0Behavior))
  564. ("V0WarnAsError", currentSettings->V0WarnAsError->Allow())
  565. ("DqDefaultAuto", currentSettings->DqDefaultAuto->Allow())
  566. ("BlockDefaultAuto", currentSettings->BlockDefaultAuto->Allow())
  567. ("SqlFlags", sqlFlagsNode);
  568. auto data = NYT::NodeToYsonString(dataNode, NYT::NYson::EYsonFormat::Binary);
  569. QContext_.GetWriter()->Put({FacadeComponent, TranslationLabel}, data).GetValueSync();
  570. } else if (QContext_.CanRead()) {
  571. auto loaded = QContext_.GetReader()->Get({FacadeComponent, TranslationLabel}).GetValueSync();
  572. if (!loaded) {
  573. return;
  574. }
  575. auto dataNode = NYT::NodeFromYsonString(loaded->Value);
  576. loadedSettings.ClusterMapping.clear();
  577. for (const auto& c : dataNode["ClusterMapping"].AsMap()) {
  578. loadedSettings.ClusterMapping[c.first] = c.second.AsString();
  579. }
  580. loadedSettings.Flags = ExtractSqlFlags(dataNode);
  581. loadedSettings.V0Behavior = (NSQLTranslation::EV0Behavior)dataNode["V0Behavior"].AsUint64();
  582. loadedSettings.V0WarnAsError = NSQLTranslation::ISqlFeaturePolicy::Make(dataNode["V0WarnAsError"].AsBool());
  583. loadedSettings.DqDefaultAuto = NSQLTranslation::ISqlFeaturePolicy::Make(dataNode["DqDefaultAuto"].AsBool());
  584. loadedSettings.BlockDefaultAuto = NSQLTranslation::ISqlFeaturePolicy::Make(dataNode["BlockDefaultAuto"].AsBool());
  585. currentSettings = &loadedSettings;
  586. }
  587. }
  588. bool TProgram::ParseYql() {
  589. YQL_PROFILE_FUNC(TRACE);
  590. YQL_ENSURE(SourceSyntax_ == ESourceSyntax::Unknown);
  591. SourceSyntax_ = ESourceSyntax::Yql;
  592. SyntaxVersion_ = 1;
  593. auto sourceCode = SourceCode_;
  594. HandleSourceCode(sourceCode);
  595. return FillParseResult(ParseAst(sourceCode));
  596. }
  597. bool TProgram::ParseSql() {
  598. YQL_PROFILE_FUNC(TRACE);
  599. static const THashMap<TString, TString> clusters = {
  600. { "plato", TString(YtProviderName) }
  601. };
  602. NSQLTranslation::TTranslationSettings settings;
  603. settings.ClusterMapping = clusters;
  604. return ParseSql(settings);
  605. }
  606. bool TProgram::ParseSql(const NSQLTranslation::TTranslationSettings& settings)
  607. {
  608. YQL_PROFILE_FUNC(TRACE);
  609. YQL_ENSURE(SourceSyntax_ == ESourceSyntax::Unknown);
  610. SourceSyntax_ = ESourceSyntax::Sql;
  611. SyntaxVersion_ = settings.SyntaxVersion;
  612. NYql::TWarningRules warningRules;
  613. auto sourceCode = SourceCode_;
  614. HandleSourceCode(sourceCode);
  615. const NSQLTranslation::TTranslationSettings* currentSettings = &settings;
  616. NSQLTranslation::TTranslationSettings loadedSettings;
  617. loadedSettings.PgParser = settings.PgParser;
  618. if (QContext_) {
  619. HandleTranslationSettings(loadedSettings, currentSettings);
  620. }
  621. return FillParseResult(SqlToYql(sourceCode, *currentSettings, &warningRules), &warningRules);
  622. }
  623. bool TProgram::Compile(const TString& username, bool skipLibraries) {
  624. YQL_PROFILE_FUNC(TRACE);
  625. Y_ENSURE(AstRoot_, "Program not parsed yet");
  626. if (!ExprCtx_) {
  627. ExprCtx_.Reset(new TExprContext(NextUniqueId_));
  628. }
  629. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_)) {
  630. return false;
  631. }
  632. TypeCtx_->IsReadOnly = true;
  633. if (!skipLibraries && Modules_.get()) {
  634. auto libs = UserDataStorage_->GetLibraries();
  635. for (auto lib : libs) {
  636. if (!Modules_->AddFromFile(lib, *ExprCtx_, SyntaxVersion_, 0)) {
  637. return false;
  638. }
  639. }
  640. }
  641. if (!CompileExpr(
  642. *AstRoot_, ExprRoot_, *ExprCtx_,
  643. skipLibraries ? nullptr : Modules_.get(),
  644. skipLibraries ? nullptr : UrlListerManager_.Get(), 0, SyntaxVersion_
  645. )) {
  646. return false;
  647. }
  648. return true;
  649. }
  650. bool TProgram::CollectUsedClusters() {
  651. using namespace NNodes;
  652. if (!UsedClusters_) {
  653. UsedClusters_.ConstructInPlace();
  654. UsedProviders_.ConstructInPlace();
  655. auto& typesCtx = *GetAnnotationContext();
  656. auto& ctx = *ExprCtx_;
  657. auto& usedClusters = *UsedClusters_;
  658. auto& usedProviders = *UsedProviders_;
  659. bool hasErrors = false;
  660. VisitExpr(ExprRoot_, [&typesCtx, &ctx, &usedClusters, &usedProviders, &hasErrors](const TExprNode::TPtr& node) {
  661. if (auto dsNode = TMaybeNode<TCoDataSource>(node)) {
  662. auto datasource = typesCtx.DataSourceMap.FindPtr(dsNode.Cast().Category());
  663. YQL_ENSURE(datasource, "Unknown DataSource: " << dsNode.Cast().Category().Value());
  664. TMaybe<TString> cluster;
  665. if (!(*datasource)->ValidateParameters(*node, ctx, cluster)) {
  666. hasErrors = true;
  667. return false;
  668. }
  669. usedProviders.insert(TString(dsNode.Cast().Category().Value()));
  670. if (cluster && *cluster != NCommon::ALL_CLUSTERS) {
  671. usedClusters.insert(*cluster);
  672. }
  673. }
  674. if (auto dsNode = TMaybeNode<TCoDataSink>(node)) {
  675. auto datasink = typesCtx.DataSinkMap.FindPtr(dsNode.Cast().Category());
  676. YQL_ENSURE(datasink, "Unknown DataSink: " << dsNode.Cast().Category().Value());
  677. TMaybe<TString> cluster;
  678. if (!(*datasink)->ValidateParameters(*node, ctx, cluster)) {
  679. hasErrors = true;
  680. return false;
  681. }
  682. usedProviders.insert(TString(dsNode.Cast().Category().Value()));
  683. if (cluster) {
  684. usedClusters.insert(*cluster);
  685. }
  686. }
  687. return true;
  688. });
  689. if (hasErrors) {
  690. UsedClusters_ = Nothing();
  691. UsedProviders_ = Nothing();
  692. return false;
  693. }
  694. }
  695. return true;
  696. }
  697. TProgram::TStatus TProgram::Discover(const TString& username) {
  698. YQL_PROFILE_FUNC(TRACE);
  699. auto m = &TProgram::DiscoverAsync;
  700. return SyncExecution(this, m, username);
  701. }
  702. TProgram::TFutureStatus TProgram::DiscoverAsync(const TString& username) {
  703. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  704. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  705. }
  706. TypeCtx_->DiscoveryMode = true;
  707. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  708. Transformer_ = TTransformationPipeline(TypeCtx_)
  709. .AddServiceTransformers()
  710. .AddParametersEvaluation(*FunctionRegistry_)
  711. .AddPreTypeAnnotation()
  712. .AddExpressionEvaluation(*FunctionRegistry_)
  713. .AddPreIOAnnotation()
  714. .Build();
  715. TFuture<void> openSession = OpenSession(username);
  716. if (!openSession.Initialized()) {
  717. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  718. }
  719. return openSession.Apply([this](const TFuture<void>& f) {
  720. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  721. try {
  722. f.GetValue();
  723. } catch (const std::exception& e) {
  724. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  725. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  726. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  727. }
  728. return AsyncTransform(*Transformer_, ExprRoot_, *ExprCtx_, false);
  729. });
  730. }
  731. TProgram::TStatus TProgram::Lineage(const TString& username, IOutputStream* traceOut, IOutputStream* exprOut, bool withTypes) {
  732. YQL_PROFILE_FUNC(TRACE);
  733. auto m = &TProgram::LineageAsync;
  734. return SyncExecution(this, m, username, traceOut, exprOut, withTypes);
  735. }
  736. TProgram::TFutureStatus TProgram::LineageAsync(const TString& username, IOutputStream* traceOut, IOutputStream* exprOut, bool withTypes) {
  737. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  738. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  739. }
  740. TypeCtx_->IsReadOnly = true;
  741. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  742. ExprStream_ = exprOut;
  743. Transformer_ = TTransformationPipeline(TypeCtx_)
  744. .AddServiceTransformers()
  745. .AddParametersEvaluation(*FunctionRegistry_)
  746. .AddPreTypeAnnotation()
  747. .AddExpressionEvaluation(*FunctionRegistry_)
  748. .AddIOAnnotation()
  749. .AddTypeAnnotation()
  750. .AddPostTypeAnnotation()
  751. .Add(TExprOutputTransformer::Sync(ExprRoot_, traceOut), "ExprOutput")
  752. .AddCheckExecution(false)
  753. .AddLineageOptimization(LineageStr_)
  754. .Add(TExprOutputTransformer::Sync(ExprRoot_, exprOut, withTypes), "AstOutput")
  755. .Build();
  756. TFuture<void> openSession = OpenSession(username);
  757. if (!openSession.Initialized())
  758. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  759. SaveExprRoot();
  760. return openSession.Apply([this](const TFuture<void>& f) {
  761. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  762. try {
  763. f.GetValue();
  764. } catch (const std::exception& e) {
  765. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  766. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  767. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  768. }
  769. return AsyncTransformWithFallback(false);
  770. });
  771. }
  772. TProgram::TStatus TProgram::Validate(const TString& username, IOutputStream* exprOut, bool withTypes) {
  773. YQL_PROFILE_FUNC(TRACE);
  774. auto m = &TProgram::ValidateAsync;
  775. return SyncExecution(this, m, username, exprOut, withTypes);
  776. }
  777. TProgram::TFutureStatus TProgram::ValidateAsync(const TString& username, IOutputStream* exprOut, bool withTypes) {
  778. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  779. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  780. }
  781. TypeCtx_->IsReadOnly = true;
  782. TVector<TDataProviderInfo> dataProviders;
  783. with_lock (DataProvidersLock_) {
  784. dataProviders = DataProviders_;
  785. }
  786. for (const auto& dp : dataProviders) {
  787. if (!dp.RemoteClusterProvider || !dp.RemoteValidate) {
  788. continue;
  789. }
  790. if (auto cluster = dp.RemoteClusterProvider(UsedClusters_, UsedProviders_, SourceSyntax_)) {
  791. return dp.RemoteValidate(*cluster, SourceSyntax_, SourceCode_, *ExprCtx_);
  792. }
  793. }
  794. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  795. ExprStream_ = exprOut;
  796. Transformer_ = TTransformationPipeline(TypeCtx_)
  797. .AddServiceTransformers()
  798. .AddParametersEvaluation(*FunctionRegistry_)
  799. .AddPreTypeAnnotation()
  800. .AddExpressionEvaluation(*FunctionRegistry_)
  801. .AddIOAnnotation()
  802. .AddTypeAnnotation()
  803. .Add(TExprOutputTransformer::Sync(ExprRoot_, exprOut, withTypes), "AstOutput")
  804. .Build();
  805. TFuture<void> openSession = OpenSession(username);
  806. if (!openSession.Initialized()) {
  807. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  808. }
  809. SaveExprRoot();
  810. return openSession.Apply([this](const TFuture<void>& f) {
  811. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  812. try {
  813. f.GetValue();
  814. } catch (const std::exception& e) {
  815. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  816. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  817. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  818. }
  819. return AsyncTransformWithFallback(false);
  820. });
  821. }
  822. TProgram::TStatus TProgram::Optimize(
  823. const TString& username,
  824. IOutputStream* traceOut,
  825. IOutputStream* tracePlan,
  826. IOutputStream* exprOut,
  827. bool withTypes)
  828. {
  829. YQL_PROFILE_FUNC(TRACE);
  830. auto m = &TProgram::OptimizeAsync;
  831. return SyncExecution(this, m, username, traceOut, tracePlan, exprOut, withTypes);
  832. }
  833. TProgram::TFutureStatus TProgram::OptimizeAsync(
  834. const TString& username,
  835. IOutputStream* traceOut,
  836. IOutputStream* tracePlan,
  837. IOutputStream* exprOut,
  838. bool withTypes)
  839. {
  840. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  841. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  842. }
  843. TypeCtx_->IsReadOnly = true;
  844. TVector<TDataProviderInfo> dataProviders;
  845. with_lock (DataProvidersLock_) {
  846. dataProviders = DataProviders_;
  847. }
  848. for (const auto& dp : dataProviders) {
  849. if (!dp.RemoteClusterProvider || !dp.RemoteOptimize) {
  850. continue;
  851. }
  852. if (auto cluster = dp.RemoteClusterProvider(UsedClusters_, UsedProviders_, SourceSyntax_)) {
  853. return dp.RemoteOptimize(*cluster,
  854. SourceSyntax_, SourceCode_, nullptr,
  855. TypeCtx_, ExprRoot_, *ExprCtx_, ExternalQueryAst_, ExternalQueryPlan_);
  856. }
  857. }
  858. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  859. ExprStream_ = exprOut;
  860. PlanStream_ = tracePlan;
  861. Transformer_ = TTransformationPipeline(TypeCtx_)
  862. .AddServiceTransformers()
  863. .AddParametersEvaluation(*FunctionRegistry_)
  864. .AddPreTypeAnnotation()
  865. .AddExpressionEvaluation(*FunctionRegistry_)
  866. .AddIOAnnotation()
  867. .AddTypeAnnotation()
  868. .AddPostTypeAnnotation()
  869. .Add(TExprOutputTransformer::Sync(ExprRoot_, traceOut), "ExprOutput")
  870. .AddOptimization()
  871. .Add(TExprOutputTransformer::Sync(ExprRoot_, exprOut, withTypes), "AstOutput")
  872. .Build();
  873. TFuture<void> openSession = OpenSession(username);
  874. if (!openSession.Initialized())
  875. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  876. SaveExprRoot();
  877. return openSession.Apply([this](const TFuture<void>& f) {
  878. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  879. try {
  880. f.GetValue();
  881. } catch (const std::exception& e) {
  882. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  883. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  884. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  885. }
  886. return AsyncTransformWithFallback(false);
  887. });
  888. }
  889. TProgram::TStatus TProgram::OptimizeWithConfig(
  890. const TString& username, const IPipelineConfigurator& pipelineConf)
  891. {
  892. YQL_PROFILE_FUNC(TRACE);
  893. auto m = &TProgram::OptimizeAsyncWithConfig;
  894. return SyncExecution(this, m, username, pipelineConf);
  895. }
  896. TProgram::TFutureStatus TProgram::OptimizeAsyncWithConfig(
  897. const TString& username, const IPipelineConfigurator& pipelineConf)
  898. {
  899. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  900. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  901. }
  902. TypeCtx_->IsReadOnly = true;
  903. TVector<TDataProviderInfo> dataProviders;
  904. with_lock (DataProvidersLock_) {
  905. dataProviders = DataProviders_;
  906. }
  907. for (const auto& dp : DataProviders_) {
  908. if (!dp.RemoteClusterProvider || !dp.RemoteOptimize) {
  909. continue;
  910. }
  911. if (auto cluster = dp.RemoteClusterProvider(UsedClusters_, UsedProviders_, SourceSyntax_)) {
  912. return dp.RemoteOptimize(*cluster,
  913. SourceSyntax_, SourceCode_, &pipelineConf,
  914. TypeCtx_, ExprRoot_, *ExprCtx_, ExternalQueryAst_, ExternalQueryPlan_);
  915. }
  916. }
  917. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  918. TTransformationPipeline pipeline(TypeCtx_);
  919. pipelineConf.AfterCreate(&pipeline);
  920. pipeline.AddServiceTransformers();
  921. pipeline.AddParametersEvaluation(*FunctionRegistry_);
  922. pipeline.AddPreTypeAnnotation();
  923. pipeline.AddExpressionEvaluation(*FunctionRegistry_);
  924. pipeline.AddIOAnnotation();
  925. pipeline.AddTypeAnnotation();
  926. pipeline.AddPostTypeAnnotation();
  927. pipelineConf.AfterTypeAnnotation(&pipeline);
  928. pipeline.AddOptimization();
  929. if (EnableRangeComputeFor_) {
  930. pipeline.Add(MakeExpandRangeComputeForTransformer(pipeline.GetTypeAnnotationContext()),
  931. "ExpandRangeComputeFor", TIssuesIds::CORE_EXEC);
  932. }
  933. pipeline.Add(CreatePlanInfoTransformer(*TypeCtx_), "PlanInfo");
  934. pipelineConf.AfterOptimize(&pipeline);
  935. Transformer_ = pipeline.Build();
  936. TFuture<void> openSession = OpenSession(username);
  937. if (!openSession.Initialized())
  938. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  939. SaveExprRoot();
  940. return openSession.Apply([this](const TFuture<void>& f) {
  941. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  942. try {
  943. f.GetValue();
  944. } catch (const std::exception& e) {
  945. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  946. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  947. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  948. }
  949. return AsyncTransformWithFallback(false);
  950. });
  951. }
  952. TProgram::TStatus TProgram::LineageWithConfig(
  953. const TString& username, const IPipelineConfigurator& pipelineConf)
  954. {
  955. YQL_PROFILE_FUNC(TRACE);
  956. auto m = &TProgram::LineageAsyncWithConfig;
  957. return SyncExecution(this, m, username, pipelineConf);
  958. }
  959. TProgram::TFutureStatus TProgram::LineageAsyncWithConfig(
  960. const TString& username, const IPipelineConfigurator& pipelineConf)
  961. {
  962. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  963. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  964. }
  965. TypeCtx_->IsReadOnly = true;
  966. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  967. TTransformationPipeline pipeline(TypeCtx_);
  968. pipelineConf.AfterCreate(&pipeline);
  969. pipeline.AddServiceTransformers();
  970. pipeline.AddParametersEvaluation(*FunctionRegistry_);
  971. pipeline.AddPreTypeAnnotation();
  972. pipeline.AddExpressionEvaluation(*FunctionRegistry_);
  973. pipeline.AddIOAnnotation();
  974. pipeline.AddTypeAnnotation();
  975. pipeline.AddPostTypeAnnotation();
  976. pipelineConf.AfterTypeAnnotation(&pipeline);
  977. pipeline.AddCheckExecution(false);
  978. pipeline.AddLineageOptimization(LineageStr_);
  979. Transformer_ = pipeline.Build();
  980. TFuture<void> openSession = OpenSession(username);
  981. if (!openSession.Initialized())
  982. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  983. SaveExprRoot();
  984. return openSession.Apply([this](const TFuture<void>& f) {
  985. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  986. try {
  987. f.GetValue();
  988. } catch (const std::exception& e) {
  989. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  990. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  991. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  992. }
  993. return AsyncTransformWithFallback(false);
  994. });
  995. }
  996. TProgram::TStatus TProgram::Run(
  997. const TString& username,
  998. IOutputStream* traceOut,
  999. IOutputStream* tracePlan,
  1000. IOutputStream* exprOut,
  1001. bool withTypes)
  1002. {
  1003. YQL_PROFILE_FUNC(TRACE);
  1004. auto m = &TProgram::RunAsync;
  1005. return SyncExecution(this, m, username, traceOut, tracePlan, exprOut, withTypes);
  1006. }
  1007. TProgram::TFutureStatus TProgram::RunAsync(
  1008. const TString& username,
  1009. IOutputStream* traceOut,
  1010. IOutputStream* tracePlan,
  1011. IOutputStream* exprOut,
  1012. bool withTypes)
  1013. {
  1014. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  1015. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1016. }
  1017. TypeCtx_->IsReadOnly = (HiddenMode_ != EHiddenMode::Disable);
  1018. TVector<TDataProviderInfo> dataProviders;
  1019. with_lock (DataProvidersLock_) {
  1020. dataProviders = DataProviders_;
  1021. }
  1022. for (const auto& dp : DataProviders_) {
  1023. if (!dp.RemoteClusterProvider || !dp.RemoteRun) {
  1024. continue;
  1025. }
  1026. if (auto cluster = dp.RemoteClusterProvider(UsedClusters_, UsedProviders_, SourceSyntax_)) {
  1027. return dp.RemoteRun(*cluster, SourceSyntax_, SourceCode_,
  1028. OutputFormat_, ResultFormat_, nullptr,
  1029. TypeCtx_, ExprRoot_, *ExprCtx_, ExternalQueryAst_, ExternalQueryPlan_, ExternalDiagnostics_,
  1030. ResultProviderConfig_);
  1031. }
  1032. }
  1033. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  1034. ExprStream_ = exprOut;
  1035. PlanStream_ = tracePlan;
  1036. TTransformationPipeline pipeline(TypeCtx_);
  1037. pipeline.AddServiceTransformers();
  1038. pipeline.AddParametersEvaluation(*FunctionRegistry_);
  1039. pipeline.AddPreTypeAnnotation();
  1040. pipeline.AddExpressionEvaluation(*FunctionRegistry_);
  1041. pipeline.AddIOAnnotation();
  1042. pipeline.AddTypeAnnotation();
  1043. pipeline.AddPostTypeAnnotation();
  1044. pipeline.Add(TExprOutputTransformer::Sync(ExprRoot_, traceOut), "ExprOutput");
  1045. pipeline.AddOptimization();
  1046. if (EnableRangeComputeFor_) {
  1047. pipeline.Add(MakeExpandRangeComputeForTransformer(pipeline.GetTypeAnnotationContext()),
  1048. "ExpandRangeComputeFor", TIssuesIds::CORE_EXEC);
  1049. }
  1050. pipeline.Add(TExprOutputTransformer::Sync(ExprRoot_, exprOut, withTypes), "AstOutput");
  1051. pipeline.Add(TPlanOutputTransformer::Sync(tracePlan, GetPlanBuilder(), OutputFormat_), "PlanOutput");
  1052. pipeline.AddRun(ProgressWriter_);
  1053. Transformer_ = pipeline.Build();
  1054. TFuture<void> openSession = OpenSession(username);
  1055. if (!openSession.Initialized()) {
  1056. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1057. }
  1058. SaveExprRoot();
  1059. return openSession.Apply([this](const TFuture<void>& f) {
  1060. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  1061. try {
  1062. f.GetValue();
  1063. } catch (const std::exception& e) {
  1064. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  1065. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  1066. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1067. }
  1068. return AsyncTransformWithFallback(false);
  1069. });
  1070. }
  1071. TProgram::TStatus TProgram::RunWithConfig(
  1072. const TString& username, const IPipelineConfigurator& pipelineConf)
  1073. {
  1074. YQL_PROFILE_FUNC(TRACE);
  1075. auto m = &TProgram::RunAsyncWithConfig;
  1076. return SyncExecution(this, m, username, pipelineConf);
  1077. }
  1078. TProgram::TFutureStatus TProgram::RunAsyncWithConfig(
  1079. const TString& username, const IPipelineConfigurator& pipelineConf)
  1080. {
  1081. if (!ProvideAnnotationContext(username)->Initialize(*ExprCtx_) || !CollectUsedClusters()) {
  1082. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1083. }
  1084. TypeCtx_->IsReadOnly = (HiddenMode_ != EHiddenMode::Disable);
  1085. TVector<TDataProviderInfo> dataProviders;
  1086. with_lock (DataProvidersLock_) {
  1087. dataProviders = DataProviders_;
  1088. }
  1089. for (const auto& dp : DataProviders_) {
  1090. if (!dp.RemoteClusterProvider || !dp.RemoteRun) {
  1091. continue;
  1092. }
  1093. if (auto cluster = dp.RemoteClusterProvider(UsedClusters_, UsedProviders_, SourceSyntax_)) {
  1094. return dp.RemoteRun(*cluster, SourceSyntax_, SourceCode_,
  1095. OutputFormat_, ResultFormat_, &pipelineConf,
  1096. TypeCtx_, ExprRoot_, *ExprCtx_, ExternalQueryAst_, ExternalQueryPlan_, ExternalDiagnostics_,
  1097. ResultProviderConfig_);
  1098. }
  1099. }
  1100. Y_ENSURE(ExprRoot_, "Program not compiled yet");
  1101. TTransformationPipeline pipeline(TypeCtx_);
  1102. pipelineConf.AfterCreate(&pipeline);
  1103. pipeline.AddServiceTransformers();
  1104. pipeline.AddParametersEvaluation(*FunctionRegistry_);
  1105. pipeline.AddPreTypeAnnotation();
  1106. pipeline.AddExpressionEvaluation(*FunctionRegistry_);
  1107. pipeline.AddIOAnnotation();
  1108. pipeline.AddTypeAnnotation();
  1109. pipeline.AddPostTypeAnnotation();
  1110. pipelineConf.AfterTypeAnnotation(&pipeline);
  1111. pipeline.AddOptimization();
  1112. if (EnableRangeComputeFor_) {
  1113. pipeline.Add(MakeExpandRangeComputeForTransformer(pipeline.GetTypeAnnotationContext()),
  1114. "ExpandRangeComputeFor", TIssuesIds::CORE_EXEC);
  1115. }
  1116. pipelineConf.AfterOptimize(&pipeline);
  1117. pipeline.AddRun(ProgressWriter_);
  1118. Transformer_ = pipeline.Build();
  1119. TFuture<void> openSession = OpenSession(username);
  1120. if (!openSession.Initialized()) {
  1121. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1122. }
  1123. SaveExprRoot();
  1124. return openSession.Apply([this](const TFuture<void>& f) {
  1125. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  1126. try {
  1127. f.GetValue();
  1128. } catch (const std::exception& e) {
  1129. YQL_LOG(ERROR) << "OpenSession error: " << e.what();
  1130. ExprCtx_->IssueManager.RaiseIssue(ExceptionToIssue(e));
  1131. return NThreading::MakeFuture<TStatus>(IGraphTransformer::TStatus::Error);
  1132. }
  1133. return AsyncTransformWithFallback(false);
  1134. });
  1135. }
  1136. void TProgram::SaveExprRoot() {
  1137. TNodeOnNodeOwnedMap deepClones;
  1138. SavedExprRoot_ = ExprCtx_->DeepCopy(*ExprRoot_, *ExprCtx_, deepClones, /*internStrings*/false, /*copyTypes*/true, /*copyResult*/false, {});
  1139. }
  1140. std::optional<bool> TProgram::CheckFallbackIssues(const TIssues& issues) {
  1141. auto isFallback = std::optional<bool>();
  1142. auto checkIssue = [&](const TIssue& issue) {
  1143. if (issue.GetCode() == TIssuesIds::DQ_GATEWAY_ERROR) {
  1144. YQL_LOG(DEBUG) << "Gateway Error " << issue;
  1145. isFallback = false;
  1146. } else if (issue.GetCode() == TIssuesIds::DQ_GATEWAY_NEED_FALLBACK_ERROR) {
  1147. YQL_LOG(DEBUG) << "Gateway Fallback Error " << issue;
  1148. isFallback = true;
  1149. } else if (issue.GetCode() == TIssuesIds::DQ_OPTIMIZE_ERROR) {
  1150. YQL_LOG(DEBUG) << "Optimize Error " << issue;
  1151. isFallback = true;
  1152. } else if (issue.GetCode() >= TIssuesIds::YT_ACCESS_DENIED &&
  1153. issue.GetCode() <= TIssuesIds::YT_FOLDER_INPUT_IS_NOT_A_FOLDER &&
  1154. (issue.GetSeverity() == TSeverityIds::S_ERROR ||
  1155. issue.GetSeverity() == TSeverityIds::S_FATAL)) {
  1156. YQL_LOG(DEBUG) << "Yt Error " << issue;
  1157. isFallback = false;
  1158. }
  1159. };
  1160. std::function<void(const TIssuePtr& issue)> recursiveCheck = [&](const TIssuePtr& issue) {
  1161. checkIssue(*issue);
  1162. for (const auto& subissue : issue->GetSubIssues()) {
  1163. recursiveCheck(subissue);
  1164. }
  1165. };
  1166. for (const auto& issue : issues) {
  1167. checkIssue(issue);
  1168. // check subissues
  1169. for (const auto& subissue : issue.GetSubIssues()) {
  1170. recursiveCheck(subissue);
  1171. }
  1172. }
  1173. return isFallback;
  1174. }
  1175. TFuture<IGraphTransformer::TStatus> TProgram::AsyncTransformWithFallback(bool applyAsyncChanges)
  1176. {
  1177. return AsyncTransform(*Transformer_, ExprRoot_, *ExprCtx_, applyAsyncChanges).Apply([this](const TFuture<IGraphTransformer::TStatus>& res) {
  1178. auto status = res.GetValueSync();
  1179. if (status == IGraphTransformer::TStatus::Error
  1180. && !TypeCtx_->ForceDq
  1181. && SavedExprRoot_
  1182. && TypeCtx_->DqCaptured
  1183. && TypeCtx_->DqFallbackPolicy != EFallbackPolicy::Never)
  1184. {
  1185. auto issues = ExprCtx_->IssueManager.GetIssues();
  1186. bool isFallback = CheckFallbackIssues(issues).value_or(true);
  1187. if (!isFallback && TypeCtx_->DqFallbackPolicy != EFallbackPolicy::Always) {
  1188. // unrecoverable error
  1189. return res;
  1190. }
  1191. ExprRoot_ = SavedExprRoot_;
  1192. SavedExprRoot_ = nullptr;
  1193. UserDataStorage_->SetUserDataTable(std::move(SavedUserDataTable_));
  1194. ExprCtx_->IssueManager.Reset();
  1195. YQL_LOG(DEBUG) << "Fallback, Issues: " << issues.ToString();
  1196. ExprCtx_->Reset();
  1197. Transformer_->Rewind();
  1198. for (auto sink : TypeCtx_->DataSinks) {
  1199. sink->Reset();
  1200. }
  1201. for (auto source : TypeCtx_->DataSources) {
  1202. source->Reset();
  1203. }
  1204. TypeCtx_->Reset();
  1205. try {
  1206. CleanupLastSession().GetValueSync();
  1207. } catch (...) {
  1208. ExprCtx_->IssueManager.RaiseIssue(TIssue({}, "Failed to cleanup session: " + CurrentExceptionMessage()));
  1209. return NThreading::MakeFuture<IGraphTransformer::TStatus>(IGraphTransformer::TStatus::Error);
  1210. }
  1211. std::function<void(const TIssuePtr& issue)> toInfo = [&](const TIssuePtr& issue) {
  1212. if (issue->Severity == TSeverityIds::S_ERROR
  1213. || issue->Severity == TSeverityIds::S_FATAL
  1214. || issue->Severity == TSeverityIds::S_WARNING)
  1215. {
  1216. issue->Severity = TSeverityIds::S_INFO;
  1217. }
  1218. for (const auto& subissue : issue->GetSubIssues()) {
  1219. toInfo(subissue);
  1220. }
  1221. };
  1222. TIssue info("DQ cannot execute the query");
  1223. info.Severity = TSeverityIds::S_INFO;
  1224. for (auto& issue : issues) {
  1225. TIssuePtr newIssue = new TIssue(issue);
  1226. if (newIssue->Severity == TSeverityIds::S_ERROR
  1227. || issue.Severity == TSeverityIds::S_FATAL
  1228. || issue.Severity == TSeverityIds::S_WARNING)
  1229. {
  1230. newIssue->Severity = TSeverityIds::S_INFO;
  1231. }
  1232. for (auto& subissue : newIssue->GetSubIssues()) {
  1233. toInfo(subissue);
  1234. }
  1235. info.AddSubIssue(newIssue);
  1236. }
  1237. ExprCtx_->IssueManager.AddIssues({info});
  1238. ++FallbackCounter_;
  1239. // don't execute recapture again
  1240. ExprCtx_->Step.Done(TExprStep::Recapture);
  1241. AbortHidden_();
  1242. return AsyncTransformWithFallback(false);
  1243. }
  1244. if (status == IGraphTransformer::TStatus::Error && (TypeCtx_->DqFallbackPolicy == EFallbackPolicy::Never || TypeCtx_->ForceDq)) {
  1245. YQL_LOG(INFO) << "Fallback skipped due to per query policy";
  1246. }
  1247. return res;
  1248. });
  1249. }
  1250. TMaybe<TString> TProgram::GetQueryAst(TMaybe<size_t> memoryLimit) {
  1251. if (ExternalQueryAst_) {
  1252. return ExternalQueryAst_;
  1253. }
  1254. TStringStream astStream;
  1255. astStream.Reserve(DEFAULT_AST_BUF_SIZE);
  1256. if (ExprRoot_) {
  1257. std::unique_ptr<IAllocator> limitingAllocator;
  1258. TConvertToAstSettings settings;
  1259. settings.AnnotationFlags = TExprAnnotationFlags::None;
  1260. settings.RefAtoms = true;
  1261. settings.Allocator = TDefaultAllocator::Instance();
  1262. if (memoryLimit) {
  1263. limitingAllocator = MakeLimitingAllocator(*memoryLimit, TDefaultAllocator::Instance());
  1264. settings.Allocator = limitingAllocator.get();
  1265. }
  1266. auto ast = ConvertToAst(*ExprRoot_, *ExprCtx_, settings);
  1267. ast.Root->PrettyPrintTo(astStream, TAstPrintFlags::ShortQuote | TAstPrintFlags::PerLine);
  1268. return astStream.Str();
  1269. } else if (AstRoot_) {
  1270. AstRoot_->PrettyPrintTo(astStream, TAstPrintFlags::ShortQuote | TAstPrintFlags::PerLine);
  1271. return astStream.Str();
  1272. }
  1273. return Nothing();
  1274. }
  1275. TMaybe<TString> TProgram::GetQueryPlan(const TPlanSettings& settings) {
  1276. if (ExternalQueryPlan_) {
  1277. return ExternalQueryPlan_;
  1278. }
  1279. if (ExprRoot_) {
  1280. TStringStream planStream;
  1281. planStream.Reserve(DEFAULT_PLAN_BUF_SIZE);
  1282. NYson::TYsonWriter writer(&planStream, OutputFormat_);
  1283. PlanBuilder_->WritePlan(writer, ExprRoot_, settings);
  1284. return planStream.Str();
  1285. }
  1286. return Nothing();
  1287. }
  1288. TMaybe<TString> TProgram::GetDiagnostics() {
  1289. if (ExternalDiagnostics_) {
  1290. return ExternalDiagnostics_;
  1291. }
  1292. if (!TypeCtx_ || !TypeCtx_->Diagnostics) {
  1293. return Nothing();
  1294. }
  1295. if (!Transformer_) {
  1296. return Nothing();
  1297. }
  1298. TStringStream out;
  1299. NYson::TYsonWriter writer(&out, DiagnosticFormat_.GetOrElse(ResultFormat_));
  1300. writer.OnBeginMap();
  1301. writer.OnKeyedItem("Write");
  1302. writer.OnBeginList();
  1303. writer.OnListItem();
  1304. writer.OnBeginMap();
  1305. writer.OnKeyedItem("Data");
  1306. writer.OnBeginMap();
  1307. writer.OnKeyedItem("Diagnostics");
  1308. writer.OnBeginMap();
  1309. writer.OnKeyedItem("TransformStats");
  1310. auto transformStats = Transformer_->GetStatistics();
  1311. NCommon::TransformerStatsToYson("", transformStats, writer);
  1312. for (auto& datasink : TypeCtx_->DataSinks) {
  1313. writer.OnKeyedItem(datasink->GetName());
  1314. if (!datasink->CollectDiagnostics(writer)) {
  1315. writer.OnEntity();
  1316. }
  1317. }
  1318. writer.OnEndMap();
  1319. writer.OnEndMap();
  1320. writer.OnEndMap();
  1321. writer.OnEndList();
  1322. writer.OnEndMap();
  1323. return out.Str();
  1324. }
  1325. IGraphTransformer::TStatistics TProgram::GetRawDiagnostics() {
  1326. return Transformer_ ? Transformer_->GetStatistics() : IGraphTransformer::TStatistics::NotPresent();
  1327. }
  1328. TMaybe<TString> TProgram::GetTasksInfo() {
  1329. if (!TypeCtx_) {
  1330. return Nothing();
  1331. }
  1332. bool hasTasks = false;
  1333. TStringStream out;
  1334. NYson::TYsonWriter writer(&out, ResultFormat_);
  1335. writer.OnBeginMap();
  1336. writer.OnKeyedItem("Write");
  1337. writer.OnBeginList();
  1338. writer.OnListItem();
  1339. writer.OnBeginMap();
  1340. writer.OnKeyedItem("Tasks");
  1341. writer.OnBeginList();
  1342. for (auto& datasink : TypeCtx_->DataSinks) {
  1343. hasTasks = hasTasks || datasink->GetTasksInfo(writer);
  1344. }
  1345. writer.OnEndList();
  1346. writer.OnEndMap();
  1347. writer.OnEndList();
  1348. writer.OnEndMap();
  1349. if (hasTasks) {
  1350. return out.Str();
  1351. } else {
  1352. return Nothing();
  1353. }
  1354. }
  1355. TMaybe<TString> TProgram::GetStatistics(bool totalOnly, THashMap<TString, TStringBuf> extraYsons) {
  1356. if (!TypeCtx_) {
  1357. return Nothing();
  1358. }
  1359. TStringStream out;
  1360. NYson::TYsonWriter writer(&out);
  1361. // Header
  1362. writer.OnBeginMap();
  1363. writer.OnKeyedItem("ExecutionStatistics");
  1364. writer.OnBeginMap();
  1365. // Providers
  1366. bool hasStatistics = false;
  1367. THashSet<TStringBuf> processed;
  1368. for (auto& datasink : TypeCtx_->DataSinks) {
  1369. TStringStream providerOut;
  1370. NYson::TYsonWriter providerWriter(&providerOut);
  1371. if (datasink->CollectStatistics(providerWriter, totalOnly)) {
  1372. writer.OnKeyedItem(datasink->GetName());
  1373. writer.OnRaw(providerOut.Str());
  1374. hasStatistics = true;
  1375. processed.insert(datasink->GetName());
  1376. }
  1377. }
  1378. for (auto& datasource : TypeCtx_->DataSources) {
  1379. if (processed.insert(datasource->GetName()).second) {
  1380. TStringStream providerOut;
  1381. NYson::TYsonWriter providerWriter(&providerOut);
  1382. if (datasource->CollectStatistics(providerWriter, totalOnly)) {
  1383. writer.OnKeyedItem(datasource->GetName());
  1384. writer.OnRaw(providerOut.Str());
  1385. hasStatistics = true;
  1386. }
  1387. }
  1388. }
  1389. auto rusage = TRusage::Get();
  1390. // System stats
  1391. writer.OnKeyedItem("system");
  1392. writer.OnBeginMap();
  1393. writer.OnKeyedItem("MaxRSS");
  1394. writer.OnBeginMap();
  1395. writer.OnKeyedItem("max");
  1396. writer.OnInt64Scalar(rusage.MaxRss);
  1397. writer.OnEndMap();
  1398. writer.OnKeyedItem("MajorPageFaults");
  1399. writer.OnBeginMap();
  1400. writer.OnKeyedItem("count");
  1401. writer.OnInt64Scalar(rusage.MajorPageFaults);
  1402. writer.OnEndMap();
  1403. if (FallbackCounter_) {
  1404. writer.OnKeyedItem("Fallback");
  1405. writer.OnBeginMap();
  1406. writer.OnKeyedItem("count");
  1407. writer.OnInt64Scalar(FallbackCounter_);
  1408. writer.OnEndMap();
  1409. }
  1410. writer.OnEndMap(); // system
  1411. // extra
  1412. for (const auto &[k, extraYson] : extraYsons) {
  1413. writer.OnKeyedItem(k);
  1414. writer.OnRaw(extraYson);
  1415. hasStatistics = true;
  1416. }
  1417. // Footer
  1418. writer.OnEndMap();
  1419. writer.OnEndMap();
  1420. if (hasStatistics) {
  1421. return out.Str();
  1422. }
  1423. return Nothing();
  1424. }
  1425. TMaybe<TString> TProgram::GetDiscoveredData() {
  1426. if (!TypeCtx_) {
  1427. return Nothing();
  1428. }
  1429. TStringStream out;
  1430. NYson::TYsonWriter writer(&out);
  1431. writer.OnBeginMap();
  1432. for (auto& datasource: TypeCtx_->DataSources) {
  1433. TStringStream providerOut;
  1434. NYson::TYsonWriter providerWriter(&providerOut);
  1435. if (datasource->CollectDiscoveredData(providerWriter)) {
  1436. writer.OnKeyedItem(datasource->GetName());
  1437. writer.OnRaw(providerOut.Str());
  1438. }
  1439. }
  1440. writer.OnEndMap();
  1441. return out.Str();
  1442. }
  1443. TMaybe<TString> TProgram::GetLineage() {
  1444. return LineageStr_;
  1445. }
  1446. TProgram::TFutureStatus TProgram::ContinueAsync() {
  1447. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  1448. return AsyncTransformWithFallback(true);
  1449. }
  1450. NThreading::TFuture<void> TProgram::Abort()
  1451. {
  1452. return CloseLastSession();
  1453. }
  1454. TIssues TProgram::Issues() const {
  1455. TIssues result;
  1456. if (ExprCtx_) {
  1457. result.AddIssues(ExprCtx_->IssueManager.GetIssues());
  1458. }
  1459. result.AddIssues(FinalIssues_);
  1460. return result;
  1461. }
  1462. TIssues TProgram::CompletedIssues() const {
  1463. TIssues result;
  1464. if (ExprCtx_) {
  1465. result.AddIssues(ExprCtx_->IssueManager.GetCompletedIssues());
  1466. }
  1467. result.AddIssues(FinalIssues_);
  1468. return result;
  1469. }
  1470. TIssue MakeNoBlocksInfoIssue(const TVector<TString>& names, bool isTypes) {
  1471. TIssue result;
  1472. TString msg = TStringBuilder() << "Most frequent " << (isTypes ? "types " : "callables ")
  1473. << "which do not support block mode: " << JoinRange(", ", names.begin(), names.end());
  1474. result.SetMessage(msg);
  1475. result.SetCode(isTypes ? TIssuesIds::CORE_TOP_UNSUPPORTED_BLOCK_TYPES : TIssuesIds::CORE_TOP_UNSUPPORTED_BLOCK_CALLABLES, TSeverityIds::S_INFO);
  1476. return result;
  1477. }
  1478. void TProgram::FinalizeIssues() {
  1479. FinalIssues_.Clear();
  1480. if (TypeCtx_) {
  1481. static const size_t topCount = 10;
  1482. auto noBlockTypes = TypeCtx_->GetTopNoBlocksTypes(topCount);
  1483. if (!noBlockTypes.empty()) {
  1484. FinalIssues_.AddIssue(MakeNoBlocksInfoIssue(noBlockTypes, true));
  1485. }
  1486. auto noBlockCallables = TypeCtx_->GetTopNoBlocksCallables(topCount);
  1487. if (!noBlockCallables.empty()) {
  1488. FinalIssues_.AddIssue(MakeNoBlocksInfoIssue(noBlockCallables, false));
  1489. }
  1490. }
  1491. }
  1492. NThreading::TFuture<void> TProgram::CleanupLastSession() {
  1493. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  1494. TString sessionId = GetSessionId();
  1495. if (sessionId.empty()) {
  1496. return MakeFuture();
  1497. }
  1498. TVector<TDataProviderInfo> dataProviders;
  1499. with_lock (DataProvidersLock_) {
  1500. dataProviders = DataProviders_;
  1501. }
  1502. TVector<NThreading::TFuture<void>> cleanupFutures;
  1503. cleanupFutures.reserve(dataProviders.size());
  1504. for (const auto& dp : dataProviders) {
  1505. if (dp.CleanupSession) {
  1506. dp.CleanupSession(sessionId);
  1507. }
  1508. if (dp.CleanupSessionAsync) {
  1509. cleanupFutures.push_back(dp.CleanupSessionAsync(sessionId));
  1510. }
  1511. }
  1512. return NThreading::WaitExceptionOrAll(cleanupFutures);
  1513. }
  1514. NThreading::TFuture<void> TProgram::CloseLastSession() {
  1515. YQL_LOG_CTX_ROOT_SESSION_SCOPE(GetSessionId());
  1516. TVector<TDataProviderInfo> dataProviders;
  1517. with_lock (DataProvidersLock_) {
  1518. dataProviders = DataProviders_;
  1519. }
  1520. auto promise = NThreading::NewPromise<void>();
  1521. TString sessionId;
  1522. with_lock(SessionIdLock_) {
  1523. // post-condition: SessionId_ will be empty
  1524. sessionId = std::move(SessionId_);
  1525. if (sessionId.empty()) {
  1526. return CloseLastSessionFuture_;
  1527. }
  1528. CloseLastSessionFuture_ = promise.GetFuture();
  1529. }
  1530. TVector<NThreading::TFuture<void>> closeFutures;
  1531. closeFutures.reserve(dataProviders.size());
  1532. for (const auto& dp : dataProviders) {
  1533. if (dp.CloseSession) {
  1534. dp.CloseSession(sessionId);
  1535. }
  1536. if (dp.CloseSessionAsync) {
  1537. closeFutures.push_back(dp.CloseSessionAsync(sessionId));
  1538. }
  1539. }
  1540. return NThreading::WaitExceptionOrAll(closeFutures)
  1541. .Apply([promise = std::move(promise)](const NThreading::TFuture<void>&) mutable {
  1542. promise.SetValue();
  1543. });
  1544. }
  1545. TString TProgram::ResultsAsString() const {
  1546. if (!ResultProviderConfig_)
  1547. return "";
  1548. TStringStream resultOut;
  1549. NYson::TYsonWriter yson(&resultOut, OutputFormat_);
  1550. yson.OnBeginList();
  1551. for (const auto& result: Results()) {
  1552. yson.OnListItem();
  1553. yson.OnRaw(result);
  1554. }
  1555. yson.OnEndList();
  1556. return resultOut.Str();
  1557. }
  1558. TTypeAnnotationContextPtr TProgram::BuildTypeAnnotationContext(const TString& username) {
  1559. auto typeAnnotationContext = MakeIntrusive<TTypeAnnotationContext>();
  1560. typeAnnotationContext->UserDataStorage = UserDataStorage_;
  1561. typeAnnotationContext->Credentials = Credentials_;
  1562. typeAnnotationContext->Modules = Modules_;
  1563. typeAnnotationContext->UrlListerManager = UrlListerManager_;
  1564. typeAnnotationContext->UdfResolver = UdfResolver_;
  1565. typeAnnotationContext->UdfIndex = UdfIndex_;
  1566. typeAnnotationContext->UdfIndexPackageSet = UdfIndexPackageSet_;
  1567. typeAnnotationContext->RandomProvider = RandomProvider_;
  1568. typeAnnotationContext->TimeProvider = TimeProvider_;
  1569. if (DiagnosticFormat_) {
  1570. typeAnnotationContext->Diagnostics = true;
  1571. }
  1572. typeAnnotationContext->ArrowResolver = ArrowResolver_;
  1573. typeAnnotationContext->FileStorage = FileStorage_;
  1574. typeAnnotationContext->QContext = QContext_;
  1575. typeAnnotationContext->HiddenMode = HiddenMode_;
  1576. if (UdfIndex_ && UdfIndexPackageSet_) {
  1577. // setup default versions at the beginning
  1578. // could be overridden by pragma later
  1579. UdfIndexPackageSet_->AddResourcesTo(UdfIndex_);
  1580. }
  1581. PlanBuilder_ = CreatePlanBuilder(*typeAnnotationContext);
  1582. THashSet<TString> providerNames;
  1583. TVector<TString> fullResultDataSinks;
  1584. TVector<std::function<TString(const TString&, const TString&)>> tokenResolvers;
  1585. for (const auto& dpi : DataProvidersInit_) {
  1586. auto dp = dpi(
  1587. username,
  1588. SessionId_,
  1589. GatewaysConfig_,
  1590. FunctionRegistry_,
  1591. RandomProvider_,
  1592. typeAnnotationContext,
  1593. ProgressWriter_,
  1594. OperationOptions_,
  1595. AbortHidden_,
  1596. QContext_
  1597. );
  1598. if (HiddenMode_ != EHiddenMode::Disable && !dp.SupportsHidden) {
  1599. continue;
  1600. }
  1601. providerNames.insert(dp.Names.begin(), dp.Names.end());
  1602. with_lock (DataProvidersLock_) {
  1603. DataProviders_.emplace_back(dp);
  1604. }
  1605. if (dp.Source) {
  1606. typeAnnotationContext->AddDataSource(dp.Names, dp.Source);
  1607. }
  1608. if (dp.Sink) {
  1609. typeAnnotationContext->AddDataSink(dp.Names, dp.Sink);
  1610. }
  1611. if (dp.TokenResolver) {
  1612. tokenResolvers.push_back(dp.TokenResolver);
  1613. }
  1614. if (dp.SupportFullResultDataSink) {
  1615. fullResultDataSinks.insert(fullResultDataSinks.end(), dp.Names.begin(), dp.Names.end());
  1616. }
  1617. }
  1618. TVector<TString> resultProviderDataSources;
  1619. if (providerNames.contains(YtProviderName)) {
  1620. resultProviderDataSources.push_back(TString(YtProviderName));
  1621. }
  1622. if (providerNames.contains(KikimrProviderName)) {
  1623. resultProviderDataSources.push_back(TString(KikimrProviderName));
  1624. }
  1625. if (providerNames.contains(RtmrProviderName)) {
  1626. resultProviderDataSources.push_back(TString(RtmrProviderName));
  1627. }
  1628. if (providerNames.contains(PqProviderName)) {
  1629. resultProviderDataSources.push_back(TString(PqProviderName));
  1630. }
  1631. if (providerNames.contains(DqProviderName)) {
  1632. resultProviderDataSources.push_back(TString(DqProviderName));
  1633. }
  1634. if (!resultProviderDataSources.empty())
  1635. {
  1636. auto resultFormat = ResultFormat_;
  1637. auto writerFactory = [resultFormat] () { return CreateYsonResultWriter(resultFormat); };
  1638. ResultProviderConfig_ = MakeIntrusive<TResultProviderConfig>(*typeAnnotationContext,
  1639. *FunctionRegistry_, ResultType_, ToString((ui32)resultFormat), writerFactory);
  1640. ResultProviderConfig_->SupportsResultPosition = SupportsResultPosition_;
  1641. auto resultProvider = CreateResultProvider(ResultProviderConfig_);
  1642. typeAnnotationContext->AddDataSink(ResultProviderName, resultProvider);
  1643. typeAnnotationContext->AvailablePureResultDataSources = resultProviderDataSources;
  1644. }
  1645. if (!fullResultDataSinks.empty()) {
  1646. typeAnnotationContext->FullResultDataSink = fullResultDataSinks.front();
  1647. }
  1648. {
  1649. auto configProvider = CreateConfigProvider(*typeAnnotationContext, GatewaysConfig_, username);
  1650. typeAnnotationContext->AddDataSource(ConfigProviderName, configProvider);
  1651. }
  1652. tokenResolvers.push_back(BuildDefaultTokenResolver(typeAnnotationContext->Credentials));
  1653. typeAnnotationContext->UserDataStorage->SetTokenResolver(BuildCompositeTokenResolver(std::move(tokenResolvers)));
  1654. return typeAnnotationContext;
  1655. }
  1656. TFuture<void> TProgram::OpenSession(const TString& username)
  1657. {
  1658. TVector<TFuture<void>> openFutures;
  1659. with_lock (DataProvidersLock_) {
  1660. for (const auto& dp : DataProviders_) {
  1661. if (dp.OpenSession) {
  1662. auto future = dp.OpenSession(SessionId_, username, ProgressWriter_, OperationOptions_,
  1663. RandomProvider_, TimeProvider_);
  1664. openFutures.push_back(future);
  1665. }
  1666. }
  1667. }
  1668. return WaitExceptionOrAll(openFutures);
  1669. }
  1670. void TProgram::Print(IOutputStream* exprOut, IOutputStream* planOut, bool cleanPlan) {
  1671. TVector<TTransformStage> printTransformers;
  1672. const auto issueCode = TIssuesIds::DEFAULT_ERROR;
  1673. if (exprOut) {
  1674. printTransformers.push_back(TTransformStage(
  1675. TExprOutputTransformer::Sync(ExprRoot_, exprOut),
  1676. "ExprOutput",
  1677. issueCode));
  1678. }
  1679. if (planOut) {
  1680. if (cleanPlan) {
  1681. GetPlanBuilder().Clear();
  1682. }
  1683. printTransformers.push_back(TTransformStage(
  1684. TPlanOutputTransformer::Sync(planOut, GetPlanBuilder(), OutputFormat_),
  1685. "PlanOutput",
  1686. issueCode));
  1687. }
  1688. auto compositeTransformer = CreateCompositeGraphTransformer(printTransformers, false);
  1689. InstantTransform(*compositeTransformer, ExprRoot_, *ExprCtx_);
  1690. }
  1691. bool TProgram::HasActiveProcesses() {
  1692. with_lock (DataProvidersLock_) {
  1693. for (const auto& dp : DataProviders_) {
  1694. if (dp.HasActiveProcesses && dp.HasActiveProcesses()) {
  1695. return true;
  1696. }
  1697. }
  1698. }
  1699. return false;
  1700. }
  1701. bool TProgram::NeedWaitForActiveProcesses() {
  1702. with_lock (DataProvidersLock_) {
  1703. for (const auto& dp : DataProviders_) {
  1704. if (dp.HasActiveProcesses && dp.HasActiveProcesses() && dp.WaitForActiveProcesses) {
  1705. return true;
  1706. }
  1707. }
  1708. }
  1709. return false;
  1710. }
  1711. } // namespace NYql