-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathtable.py
More file actions
3264 lines (2844 loc) · 113 KB
/
Copy pathtable.py
File metadata and controls
3264 lines (2844 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © 2026 Pathway
from __future__ import annotations
import functools
import warnings
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast, overload
import pathway.internals.column as clmn
import pathway.internals.expression as expr
from pathway.engine import ExternalIndexFactory
from pathway.internals import api, dtype as dt, groupbys, thisclass, universes
from pathway.internals.api import Value
from pathway.internals.arg_handlers import (
arg_handler,
groupby_handler,
reduce_args_handler,
select_args_handler,
)
from pathway.internals.decorators import contextualized_operator
from pathway.internals.desugaring import (
RestrictUniverseDesugaring,
combine_args_kwargs,
desugar,
)
from pathway.internals.expression_visitor import collect_tables
from pathway.internals.helpers import SetOnceProperty, StableSet
from pathway.internals.joins import Joinable, JoinResult
from pathway.internals.operator import DebugOperator, OutputHandle
from pathway.internals.operator_input import OperatorInput
from pathway.internals.parse_graph import G
from pathway.internals.runtime_type_check import check_arg_types
from pathway.internals.schema import Schema, schema_from_columns, schema_from_types
from pathway.internals.table_like import TableLike
from pathway.internals.table_slice import TableSlice
from pathway.internals.trace import trace_user_frame
from pathway.internals.type_interpreter import TypeInterpreterState
from pathway.internals.universe import Universe
from pathway.internals.universe_solver import UniverseSolver
if TYPE_CHECKING:
from pathway.internals.datasink import DataSink
from pathway.internals.interactive import LiveTable
from pathway.stdlib.temporal.utils import IntervalType
TSchema = TypeVar("TSchema", bound=Schema)
TTable = TypeVar("TTable", bound="Table[Any]")
T = TypeVar("T", bound=api.Value)
class Table(
Joinable,
OperatorInput,
Generic[TSchema],
):
"""Collection of named columns over identical universes.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... age | owner | pet
... 10 | Alice | dog
... 9 | Bob | dog
... 8 | Alice | cat
... 7 | Bob | dog
... ''')
>>> isinstance(t1, pw.Table)
True
"""
if TYPE_CHECKING:
from pathway.stdlib.ordered import diff # type: ignore[misc]
from pathway.stdlib.statistical import interpolate # type: ignore[misc]
from pathway.stdlib.temporal import ( # type: ignore[misc]
add_update_timestamp_utc,
asof_join,
asof_join_left,
asof_join_outer,
asof_join_right,
asof_now_join,
asof_now_join_inner,
asof_now_join_left,
inactivity_detection,
interval_join,
interval_join_inner,
interval_join_left,
interval_join_outer,
interval_join_right,
window_join,
window_join_inner,
window_join_left,
window_join_outer,
window_join_right,
windowby,
)
from pathway.stdlib.viz import ( # type: ignore[misc]
_repr_mimebundle_,
plot,
show,
)
_columns: dict[str, clmn.Column]
_schema: type[Schema]
_id_column: clmn.IdColumn
_rowwise_context: clmn.RowwiseContext
_source: SetOnceProperty[OutputHandle] = SetOnceProperty()
"""Lateinit by operator."""
def __init__(
self,
_columns: Mapping[str, clmn.Column],
_context: clmn.Context,
_schema: type[Schema] | None = None,
):
if _schema is None:
_schema = schema_from_columns(_columns, _context.id_column)
super().__init__(_context)
self._columns = dict(_columns)
self._schema = _schema
self._id_column = _context.id_column
assert dt.wrap(self._id_column.dtype) == dt.wrap(self._schema.id_type)
self._substitution = {thisclass.this: self}
self._rowwise_context = clmn.RowwiseContext(self._id_column)
@property
def id(self) -> expr.ColumnReference:
"""Get reference to pseudocolumn containing id's of a table.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... age | owner | pet
... 10 | Alice | dog
... 9 | Bob | dog
... 8 | Alice | cat
... 7 | Bob | dog
... ''')
>>> t2 = t1.select(ids = t1.id)
>>> t2.typehints()['ids']
<class 'pathway.engine.Pointer'>
>>> pw.debug.compute_and_print(t2.select(test=t2.id == t2.ids), include_id=False)
test
True
True
True
True
"""
return expr.ColumnReference(_table=self, _column=self._id_column, _name="id")
def column_names(self):
return self.keys()
def keys(self):
return self._columns.keys()
def _get_column(self, name: str) -> clmn.Column:
return self._columns[name]
def _ipython_key_completions_(self):
return list(self.column_names())
def __dir__(self):
return list(super().__dir__()) + list(self.column_names())
@property
def _C(self) -> TSchema:
return self.C # type: ignore
@property
def schema(self) -> type[Schema]:
"""Get schema of the table.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... age | owner | pet
... 10 | Alice | dog
... 9 | Bob | dog
... 8 | Alice | cat
... 7 | Bob | dog
... ''')
>>> t1.schema
<pathway.Schema types={'age': <class 'int'>, 'owner': <class 'str'>, 'pet': <class 'str'>}, \
id_type=<class 'pathway.engine.Pointer'>>
>>> t1.typehints()['age']
<class 'int'>
"""
return self._schema
@property
def is_append_only(self) -> bool:
return all([col.properties.append_only for col in self._columns.values()])
def _get_colref_by_name(self, name, exception_type) -> expr.ColumnReference:
name = self._column_deprecation_rename(name)
if name == "id":
return self.id
if name not in self.keys():
raise exception_type(f"Table has no column with name {name}.")
return expr.ColumnReference(
_table=self, _column=self._get_column(name), _name=name
)
@overload
def __getitem__(self, args: str | expr.ColumnReference) -> expr.ColumnReference: ...
@overload
def __getitem__(self, args: list[str | expr.ColumnReference]) -> Table: ...
@trace_user_frame
def __getitem__(
self, args: str | expr.ColumnReference | list[str | expr.ColumnReference]
) -> expr.ColumnReference | Table:
"""Get columns by name.
Warning:
- Does not allow repetitions of columns.
- Fails if tries to access nonexistent column.
Args:
names: a singe column name or list of columns names to be extracted from `self`.
Returns:
Table with specified columns, or column expression (if single argument given).
Instead of column names, column references are valid here.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... age | owner | pet
... 10 | Alice | dog
... 9 | Bob | dog
... 8 | Alice | cat
... 7 | Bob | dog
... ''')
>>> t2 = t1[["age", "pet"]]
>>> t2 = t1[["age", t1.pet]]
>>> pw.debug.compute_and_print(t2, include_id=False)
age | pet
7 | dog
8 | cat
9 | dog
10 | dog
"""
if isinstance(args, expr.ColumnReference):
if (args.table is not self) and not isinstance(
args.table, thisclass.ThisMetaclass
):
raise ValueError(
"Table.__getitem__ argument has to be a ColumnReference to the same table or pw.this, or a string "
+ "(or a list of those)."
)
return self._get_colref_by_name(args.name, KeyError)
elif isinstance(args, str):
return self._get_colref_by_name(args, KeyError)
else:
return self.select(*[self[name] for name in args])
@staticmethod
def _get_universe_solver() -> UniverseSolver:
return G.universe_solver
@trace_user_frame
@staticmethod
@check_arg_types
def from_columns(
*args: expr.ColumnReference, **kwargs: expr.ColumnReference
) -> Table:
"""Build a table from columns.
All columns must have the same ids. Columns' names must be pairwise distinct.
Args:
args: List of columns.
kwargs: Columns with their new names.
Returns:
Table: Created table.
Example:
>>> import pathway as pw
>>> t1 = pw.Table.empty(age=float, pet=float)
>>> t2 = pw.Table.empty(foo=float, bar=float).with_universe_of(t1)
>>> t3 = pw.Table.from_columns(t1.pet, qux=t2.foo)
>>> pw.debug.compute_and_print(t3, include_id=False)
pet | qux
"""
all_args = cast(
dict[str, expr.ColumnReference], combine_args_kwargs(args, kwargs)
)
if not all_args:
raise ValueError("Table.from_columns() cannot have empty arguments list")
else:
arg = next(iter(all_args.values()))
table: Table = arg.table
for arg in all_args.values():
if not table._universe.is_equal_to(arg.table._universe):
raise ValueError(
"Universes of all arguments of Table.from_columns() have to be equal.\n"
+ "Consider using Table.promise_universes_are_equal() to assert it.\n"
+ "(However, untrue assertion might result in runtime errors.)"
)
return table.select(*args, **kwargs)
@trace_user_frame
@check_arg_types
def concat_reindex(self, *tables: Table) -> Table:
"""Concatenate contents of several tables.
This is similar to PySpark union. All tables must have the same schema. Each row is reindexed.
Args:
tables: List of tables to concatenate. All tables must have the same schema.
Returns:
Table: The concatenated table. It will have new, synthetic ids.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... | pet
... 1 | Dog
... 7 | Cat
... ''')
>>> t2 = pw.debug.table_from_markdown('''
... | pet
... 1 | Manul
... 8 | Octopus
... ''')
>>> t3 = t1.concat_reindex(t2)
>>> pw.debug.compute_and_print(t3, include_id=False)
pet
Cat
Dog
Manul
Octopus
"""
all_tables: list[Table] = [self, *tables]
all_tables = [table.update_id_type(dt.ANY_POINTER) for table in all_tables]
reindexed = [
table.with_id_from(table.id, i) for i, table in enumerate(all_tables)
]
universes.promise_are_pairwise_disjoint(*reindexed)
concatenated = Table.concat(*reindexed)
return concatenated.update_id_type(
dt.ANY_POINTER,
id_append_only=concatenated._id_column.properties.append_only,
)
@trace_user_frame
@staticmethod
@check_arg_types
def empty(**kwargs) -> Table:
"""Creates an empty table with a schema specified by kwargs.
Args:
kwargs: Dict whose keys are column names and values are column types.
Returns:
Table: Created empty table.
Example:
>>> import pathway as pw
>>> t1 = pw.Table.empty(age=float, pet=float)
>>> pw.debug.compute_and_print(t1, include_id=False)
age | pet
"""
from pathway.internals import table_io
ret = table_io.empty_from_schema(schema_from_types(None, **kwargs))
ret._universe.register_as_empty(no_warn=True)
return ret
@trace_user_frame
@desugar
@arg_handler(handler=select_args_handler)
@contextualized_operator
def select(self, *args: expr.ColumnReference, **kwargs: Any) -> Table:
"""Build a new table with columns specified by kwargs.
Output columns' names are keys(kwargs). values(kwargs) can be raw values, boxed
values, columns. Assigning to id reindexes the table.
Args:
args: Column references.
kwargs: Column expressions with their new assigned names.
Returns:
Table: Created table.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... pet
... Dog
... Cat
... ''')
>>> t2 = t1.select(animal=t1.pet, desc="fluffy")
>>> pw.debug.compute_and_print(t2, include_id=False)
animal | desc
Cat | fluffy
Dog | fluffy
"""
new_columns = []
all_args = combine_args_kwargs(args, kwargs)
for new_name, expression in all_args.items():
self._validate_expression(expression)
column = self._eval(expression)
new_columns.append((new_name, column))
return self._with_same_universe(*new_columns)
@trace_user_frame
def __add__(self, other: Table) -> Table:
"""Build a union of `self` with `other`.
Semantics: Returns a table C, such that
- C.columns == self.columns + other.columns
- C.id == self.id == other.id
Args:
other: The other table. `self.id` must be equal `other.id` and
`self.columns` and `other.columns` must be disjoint (or overlapping names
are THE SAME COLUMN)
Returns:
Table: Created table.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... pet
... 1 Dog
... 7 Cat
... ''')
>>> t2 = pw.debug.table_from_markdown('''
... age
... 1 10
... 7 3
... ''')
>>> t3 = t1 + t2
>>> pw.debug.compute_and_print(t3, include_id=False)
pet | age
Cat | 3
Dog | 10
"""
if not self._universe.is_equal_to(other._universe):
raise ValueError(
"Universes of all arguments of Table.__add__() have to be equal.\n"
+ "Consider using Table.promise_universes_are_equal() to assert it.\n"
+ "(However, untrue assertion might result in runtime errors.)"
)
return self.select(*self, *other)
@property
def slice(self) -> TableSlice:
"""Creates a collection of references to self columns.
Supports basic column manipulation methods.
Example:
>>> import pathway as pw
>>> t1 = pw.debug.table_from_markdown('''
... age | owner | pet
... 10 | Alice | dog
... 9 | Bob | dog
... 8 | Alice | cat
... 7 | Bob | dog
... ''')
>>> t1.slice.without("age")
TableSlice({'owner': <table1>.owner, 'pet': <table1>.pet})
"""
return TableSlice(dict(**self), self)
@trace_user_frame
@desugar
@check_arg_types
def filter(self, filter_expression: expr.ColumnExpression) -> Table[TSchema]:
"""Filter a table according to `filter_expression` condition.
Args:
filter_expression: `ColumnExpression` that specifies the filtering condition.
Returns:
Table: Result has the same schema as `self` and its ids are subset of `self.id`.
Example:
>>> import pathway as pw
>>> vertices = pw.debug.table_from_markdown('''
... label outdegree
... 1 3
... 7 0
... ''')
>>> filtered = vertices.filter(vertices.outdegree == 0)
>>> pw.debug.compute_and_print(filtered, include_id=False)
label | outdegree
7 | 0
"""
filter_type = self.eval_type(filter_expression)
if filter_type != dt.BOOL:
raise TypeError(
f"Filter argument of Table.filter() has to be bool, found {filter_type}."
)
ret = self._filter(filter_expression)
if (
filter_col := expr.get_column_filtered_by_is_none(filter_expression)
) is not None and filter_col.table == self:
name = filter_col.name
dtype = self._columns[name].dtype
ret = ret.update_types(**{name: dt.unoptionalize(dtype)})
return ret
@trace_user_frame
@desugar
@check_arg_types
def split(
self, split_expression: expr.ColumnExpression
) -> tuple[Table[TSchema], Table[TSchema]]:
"""Split a table according to `split_expression` condition.
Args:
split_expression: `ColumnExpression` that specifies the split condition.
Returns:
positive_table, negative_table: tuple of tables,
with the same schemas as `self` and with ids that are subsets of `self.id`,
and provably disjoint.
Example:
>>> import pathway as pw
>>> vertices = pw.debug.table_from_markdown('''
... label outdegree
... 1 3
... 7 0
... ''')
>>> positive, negative = vertices.split(vertices.outdegree == 0)
>>> pw.debug.compute_and_print(positive, include_id=False)
label | outdegree
7 | 0
>>> pw.debug.compute_and_print(negative, include_id=False)
label | outdegree
1 | 3
"""
positive = self.filter(split_expression)
negative = self.filter(~split_expression)
universes.promise_are_pairwise_disjoint(positive, negative)
universes.promise_are_equal(
self, Table.concat(positive, negative)
) # TODO: add API method for this
return positive, negative
@contextualized_operator
def _filter(self, filter_expression: expr.ColumnExpression) -> Table[TSchema]:
self._validate_expression(filter_expression)
filtering_column = self._eval(filter_expression)
assert self._universe == filtering_column.universe
context = clmn.FilterContext(filtering_column, self._id_column)
return self._table_with_context(context)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def _external_index_as_of_now(
self,
query_table: Table,
*,
index_column: expr.ColumnExpression,
query_column: expr.ColumnExpression,
index_factory: ExternalIndexFactory,
res_type: dt.DType = dt.List(dt.Tuple(dt.ANY_POINTER, float)),
query_responses_limit_column: expr.ColumnExpression | None = None,
index_filter_data_column: expr.ColumnExpression | None = None,
query_filter_column: expr.ColumnExpression | None = None,
) -> Table:
ev_query_responses_limit_column = (
query_table._eval(query_responses_limit_column)
if query_responses_limit_column is not None
else None
)
ev_index_filter_data_column = (
self._eval(index_filter_data_column)
if index_filter_data_column is not None
else None
)
ev_query_filter_column = (
query_table._eval(query_filter_column)
if query_filter_column is not None
else None
)
context = clmn.ExternalIndexAsOfNowContext(
_index_id_column=self._id_column,
_query_id_column=query_table._id_column,
index_table=self,
query_table=query_table,
index_column=self._eval(index_column),
query_column=query_table._eval(query_column),
index_factory=index_factory,
query_response_limit_column=ev_query_responses_limit_column,
index_filter_data_column=ev_index_filter_data_column,
query_filter_column=ev_query_filter_column,
res_type=res_type,
)
return Table(
_columns={"_pw_index_reply": context.index_reply}, _context=context
)
@trace_user_frame
@desugar
@check_arg_types
def _gradual_broadcast(
self,
threshold_table,
lower_column,
value_column,
upper_column,
) -> Table:
return self + self.__gradual_broadcast(
threshold_table, lower_column, value_column, upper_column
)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def __gradual_broadcast(
self,
threshold_table,
lower_column,
value_column,
upper_column,
):
context = clmn.GradualBroadcastContext(
self._id_column,
threshold_table._eval(lower_column),
threshold_table._eval(value_column),
threshold_table._eval(upper_column),
)
return Table(_columns={"apx_value": context.apx_value_column}, _context=context)
@trace_user_frame
@desugar
def forget(
self,
time_column: expr.ColumnExpression,
threshold: IntervalType,
mark_forgetting_records: bool = False,
) -> Table[TSchema]:
"""Remove old entries when they start to satisfy ``time_column <= max(time_column) - threshold``.
This operator is useful for removing old entries from the stateful operators
downstream (like joins, groupbys etc.). It stores the entries and when the
current time (defined as max over all ``time_column`` values so far) reaches
their time plus ``threshold``, a deletion of entries is emitted.
Args:
time_column: ``ColumnExpression`` that specifies the event time.
threshold: value used to determine which entries are old enough to be removed.
Should match the type of the ``time_column`` (``int -> int``,
``float -> float``, ``datetime -> timedelta``).
mark_forgetting_records : If set to ``True``, Pathway Live Data Framework marks records
corresponding to the deletion of expired entries in a special way,
without changing their visible representation.
This flag is useful when combined with ``filter_out_results_of_forgetting``,
which can later remove those marked deletion records. In other words, it
allows you to revert the effects of forgetting at a later stage.
Example:
>>> import pathway as pw
>>> t = pw.debug.table_from_markdown(
... '''
... t | v | __time__
... 1 | 1 | 2
... 2 | 1 | 2
... 4 | 2 | 4
... 3 | 3 | 6
... '''
... )
>>> t_with_forgetting = t.forget(pw.this.t, 3)
>>> s = pw.debug.table_from_markdown(
... '''
... v | a | __time__
... 1 | 1 | 2
... 2 | 2 | 4
... 1 | 3 | 8
... '''
... )
>>> res = t_with_forgetting.join(s, pw.left.v == pw.right.v).select(
... pw.left.t, pw.left.v, pw.right.a
... )
>>> pw.debug.compute_and_print_update_stream(res)
| t | v | a | __time__ | __diff__
^YYYD8ZW... | 1 | 1 | 1 | 2 | 1
^YYY47FZ... | 2 | 1 | 1 | 2 | 1
^Z3QTSKY... | 4 | 2 | 2 | 4 | 1
^YYYD8ZW... | 1 | 1 | 1 | 6 | -1
^YYY822X... | 2 | 1 | 3 | 8 | 1
The entry ``t=1,v=1`` is forgotten at the processing time 6. It gets removed from the
join. When at the processing time 8, there's a new entry with the join key equal to 1,
it only gets joined with ``t=2,v=1`` entry because the other entry was already removed.
The removal of ``t=1,v=1`` entry resulted in the retraction of all its results from a join
(only ``t=1,v=1,a=1`` in this case). If you would like to filter out retractions,
you can do ``to_stream().filter(pw.this.is_upsert)`` on the result of a join.
For cases where you don't need to permanently forget data across the entire
pipeline, but only want to temporarily limit the dataset to a specific time
window for a computation, and then return to processing the full data stream,
you can use the parameter ``mark_forgetting_records`` set to ``True`` to achieve
this.
For example:
>>> t_with_forgetting = t.forget(pw.this.t, 3)
>>> # You computation on a t_with_forgetting, bounded by the 3 time units
>>> t = t_with_forgetting.filter_out_results_of_forgetting()
This way, your table will be temporarily windowed, computations can be applied,
and then the stream will return to its normal state.
"""
return self._forget(
time_column + threshold,
time_column,
mark_forgetting_records=mark_forgetting_records,
)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def _forget(
self,
threshold_column: expr.ColumnExpression,
time_column: expr.ColumnExpression,
mark_forgetting_records: bool,
instance_column: expr.ColumnExpression | None = None,
) -> Table[TSchema]:
if instance_column is None:
instance_column = expr.ColumnConstExpression(None)
context = clmn.ForgetContext(
self._id_column,
self._eval(threshold_column),
self._eval(time_column),
self._eval(instance_column),
mark_forgetting_records,
)
return self._table_with_context(context)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def _forget_immediately(
self,
) -> Table:
context = clmn.ForgetImmediatelyContext(self._id_column)
return self._table_with_context(context)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def filter_out_results_of_forgetting(
self, ensure_consistency: bool = False
) -> Table:
"""
Remove all row-deletion events from the table that were produced by the
``forget`` method.
This method has an effect only if ``forget`` was previously called with
``mark_forgetting_records`` parameter set to ``True``. Only the deletions that
are triggered by forgetting will be removed.
Args:
ensure_consistency: When enabled, the Pathway Live Data Framework keeps track of the latest value for
each key. This ensures that when entries emitted by forgetting are removed,
the sequence of remaining additions and deletions stays consistent.
For example, if an entry is removed due to forgetting and another entry with
the same key appears afterward, the stream would normally have two additions
for the same key, which is inconsistent. With the flag enabled, the Pathway Live Data Framework
tracks the state of each key. It will emit a deletion before the second
addition, guaranteeing that the stream remains consistent. Note that this
feature uses additional memory to store the current snapshot of the table.
If your data and use case guarantee that such inconsistencies won't occur,
you can leave this check disabled.
Note:
Using ``forget`` with a set ``mark_forgetting_records`` immediately followed by
``filter_out_results_of_forgetting`` is effectively a no-op.
The first call produces a table that temporarily contains both original
and "forgotten" records, each forgotten record appears as an event
with the ``diff`` equal to ``-1``. The second call removes those deletion events
and restores the table to its original state.
The method is, however, useful when you perform intermediate computations between
these two calls. For example, you can call ``forget`` with a certain time window
to limit the scope of processing, effectively creating a bounded window of data.
Within that window, you can perform computations that benefit from this limited dataset.
After those computations, calling ``filter_out_results_of_forgetting``
removes all deletion events and restores the table to a consistent state in which
the previous forgetting operation is undone, and you have the complete set of rows,
no longer limited to the forgetting window.
This approach lets you compute metrics inside a bounded window and then
continue processing the entire data stream without carrying forward
deletions for old records. Downstream consumers will receive fewer events because
only insertions are propagated further.
"""
# The output universe is a superset of input universe because forgetting entries
# are filtered out. At each point in time, the set of keys with +1 diff can be
# bigger than a set of keys with +1 diff in an input table.
context = clmn.FilterOutForgettingContext(
self._id_column, ensure_consistency=ensure_consistency
)
return self._table_with_context(context)
@trace_user_frame
@desugar
def ignore_late(
self, time_column: expr.ColumnExpression, threshold: IntervalType
) -> Table[TSchema]:
"""Filter out entries that satisfy ``time_column <= max(time_column) - threshold``.
In contrast to ``forget``, this operator doesn't store the entries. It just checks
if the entries match the condition and, if they do, allows them to pass. The only
value stored by this operator is the current time (defined as max over all
``time_column`` values so far).
Please note that if the table is non-append-only and there's a difference in
processing time between an insertion and a deletion for some key, the insertion
may pass through but the deletion may be filtered out. It'll happen if the max
value in ``time_column`` advanced between the insertion and deletion and the insertion
didn't satisfy the filtering-out criterion but the deletion did.
Args:
time_column: ``ColumnExpression`` that specifies the event time.
threshold: value used to determine which entries should be filtered out.
Should match the type of the ``time_column`` (``int -> int``,
``float -> float``, ``datetime -> timedelta``).
Example:
>>> import pathway as pw
>>> t = pw.debug.table_from_markdown(
... '''
... t | v | __time__
... 1 | 1 | 2
... 2 | 2 | 4
... 5 | 3 | 6
... 2 | 4 | 8
... 7 | 5 | 10
... '''
... )
>>> res = t.ignore_late(pw.this.t, 3)
>>> pw.debug.compute_and_print_update_stream(res)
| t | v | __time__ | __diff__
^X1MXHYY... | 1 | 1 | 2 | 1
^YYY4HAB... | 2 | 2 | 4 | 1
^Z3QWT29... | 5 | 3 | 6 | 1
^3HN31E1... | 7 | 5 | 10 | 1
"""
return self._freeze(time_column + threshold, time_column)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def _freeze(
self,
threshold_column: expr.ColumnExpression,
time_column: expr.ColumnExpression,
instance_column: expr.ColumnExpression | None = None,
) -> Table[TSchema]:
# FIXME: freeze can be incorrect if the input is not append-only
# we may produce insertion but never produce deletion
if instance_column is None:
instance_column = expr.ColumnConstExpression(None)
context = clmn.FreezeContext(
self._id_column,
self._eval(threshold_column),
self._eval(time_column),
self._eval(instance_column),
)
return self._table_with_context(context)
@trace_user_frame
@desugar
def buffer(
self, time_column: expr.ColumnExpression, threshold: IntervalType
) -> Table[TSchema]:
"""Buffers the values until the condition ``time_column <= max(time_column) - threshold`` is met.
This is a stateful operator. It stores the entries if their
``time_column > max(time_column) - threshold``. Otherwise the entries can pass immediately.
Once the current time (defined as max over all ``time_column`` values so far) advances and
some of the stored entries start to satisfy the condition, they are sent for further processing.
Args:
time_column: ``ColumnExpression`` that specifies the event time.
threshold: value used to determine which entries are old enough to be sent for further processing.
Should match the type of the ``time_column`` (``int -> int``,
``float -> float``, ``datetime -> timedelta``).
Example:
>>> import pathway as pw
>>> t = pw.debug.table_from_markdown(
... '''
... t | v | __time__
... 1 | 1 | 2
... 2 | 2 | 4
... 5 | 3 | 6
... 2 | 4 | 8
... 7 | 5 | 10
... '''
... )
>>> res = t.buffer(pw.this.t, 3)
>>> pw.debug.compute_and_print_update_stream(res)
| t | v | __time__ | __diff__
^X1MXHYY... | 1 | 1 | 6 | 1
^YYY4HAB... | 2 | 2 | 6 | 1
^3CZ78B4... | 2 | 4 | 8 | 1
^Z3QWT29... | 5 | 3 | 18446744073709551614 | 1
^3HN31E1... | 7 | 5 | 18446744073709551614 | 1
The values of processing time for rows with event time 5, 7 are equal
to 18446744073709551614 because there's no more input and they are released
only at the end of the processing. 18446744073709551614 is the maximum
possible time.
"""
return self._buffer(time_column + threshold, time_column)
@trace_user_frame
@desugar
@check_arg_types
@contextualized_operator
def _buffer(
self,
threshold_column: expr.ColumnExpression,
time_column: expr.ColumnExpression,
instance_column: expr.ColumnExpression | None = None,
) -> Table:
if instance_column is None:
instance_column = expr.ColumnConstExpression(None)
context = clmn.BufferContext(
self._id_column,
self._eval(threshold_column),
self._eval(time_column),
self._eval(instance_column),
)
return self._table_with_context(context)
@contextualized_operator
@check_arg_types
def difference(self, other: Table) -> Table[TSchema]:
r"""Restrict self universe to keys not appearing in the other table.
Args:
other: table with ids to remove from self.
Returns:
Table: table with restricted universe, with the same set of columns
Example:
>>> import pathway as pw