[syndicated profile] register_security_feed

Posted by Thomas Claburn

Security, not model performance, is what's stalling adoption

Interview  Before AI becomes commonplace in enterprises, corporate leaders have to commit to an ongoing security testing regime tuned to the nuances of AI models.…

[syndicated profile] planetposgresql_feed

I recently had a customer that wanted to leverage read replicas to ensure that their read queries were not going to impeded with work being done on the primary instance and also required an SLA of at worst a few seconds. Ultimately they weren’t meeting the SLA and my colleagues and I were asked to look at what was going on.

The first thing we came to understand is that the pattern of work on the primary is a somewhat frequent large DELETE statement followed by a data refresh accomplished by a COPY from STDIN command against a partitioned table with 16 hash partitions.

The problem being observed was that periodically the SELECTs occurring on the read replica would time out and not meet the SLA. Upon investigation, we found that the “startup” process on the read replica would periodically request an “exclusive lock” on some random partition. This exclusive lock would block the SELECT (which is partition unaware) and then cause the timeout. But what is causing the timeout?

After spending some time investigating, the team was able to correlate the exclusive lock with a routine “autovacuum” occurring on the primary. But why was it locking? After inspection of the WAL, it turns out that it the issue was due to a step in the vacuum process whereby it tries to return free pages at the end of the table back to the OS, truncation of the High Water Mark (HWM). Essentially the lock is requested on the primary and then transmitted to the replica via the WAL so that the tables can be kept consistent.

To confirm that it was in fact the step in VACUUM that truncates the HWM, we decided to alter each partition of the table to allow VACUUM to skip that step:

ALTER TABLE [table name / partition name] SET (vacuum_truncate = false);

After letting this run for 24 hours, we in fact saw no further blocking locks causing SLA misses on the replicas. Should we worry about shrinking the High Water Mark (HWM)? Well as with everything in IT, it depends. Other DBMS engines like Oracle do not shrink the High Water Mark (HWM), typically maintenance operations such as DBMS_REDEF or ALTER TABLE … SHRINK SPACE / SHRINK SPACE COMPACT deal with that. So now that we are talking about PostgreSQL do we need to worry about it? This is where the pg_freespacemap extension can help. We can use this extension and a script to check to see if in fact the High Water Mark (HWM) is growing or staying put. If it is growing, we can just execute a regular VACUUM with an additional option called TRUNCATE to handle it:

VACUUM (verbose, truncate) [schema].[table name];

When you do this, you will see one additional message in the VACUUM output signifying that the VACUUM truncated the High Water Mark (HWM):

INFO:  table "large_table": truncated 302534 to 302233 pages

As I stated earlier, we can use pg_freespacemap to see if we actually need to worry about the High Water Mark (HWM) growing. I could have taken a lot of time to write a script to figure it out, but instead, I enlisted Google Gemini to see what it would come up with. After a few iterations, the output was nearly perfect!

CREATE EXTENSION pg_freespacemap;

CREATE OR REPLACE FUNCTION show_empty_pages(p_table_name TEXT)
RETURNS VOID AS $$
DECLARE
    -- Core processing variables
    table_oid_regclass  REGCLASS;
    block_size          BIGINT;
    fsm_granularity     BIGINT;
    max_fsm_free_space  BIGINT;
    total_pages         BIGINT;
    high_water_mark     BIGINT := 0;

    -- Variables for the final summary
    first_empty_block   BIGINT;
    free_pages_at_end   BIGINT;
    free_space_at_end   TEXT;
BEGIN
    -- Setup
    table_oid_regclass := p_table_name::regclass;
    block_size  := current_setting('block_size')::bigint;
    SELECT relpages INTO total_pages FROM pg_class WHERE oid = table_oid_regclass;
    fsm_granularity    := block_size / 256;
    max_fsm_free_space := floor((block_size - 24) / fsm_granularity) * fsm_granularity;

    --------------------------------------------------------------------------------
    -- PASS 1: FIND THE HIGH-WATER MARK (last page with data)
    --------------------------------------------------------------------------------
    FOR i IN REVERSE (total_pages - 1)..0 LOOP
        IF pg_freespace(table_oid_regclass, i) < max_fsm_free_space THEN
            high_water_mark := i;
            EXIT;
        END IF;
    END LOOP;

    --------------------------------------------------------------------------------
    -- FINAL STEP: CALCULATE AND RAISE THE SUMMARY NOTICE
    --------------------------------------------------------------------------------
    first_empty_block := high_water_mark + 1;
    free_pages_at_end := total_pages - first_empty_block;
    IF free_pages_at_end < 0 THEN
        free_pages_at_end := 0;
    END IF;
    free_space_at_end := pg_size_pretty(free_pages_at_end * block_size);

    RAISE NOTICE '-------------------------------------------------------------';
    RAISE NOTICE 'Summary for table: %', p_table_name;
    RAISE NOTICE '-------------------------------------------------------------';
    RAISE NOTICE 'The High Water Mark (HWM) is at page: %', total_pages;
    IF total_pages <> first_empty_block THEN
    	RAISE NOTICE 'First potentially empty page is at: %', first_empty_block;
    	RAISE NOTICE 'Total Pages in Table: %', total_pages;
    	RAISE NOTICE 'Number of potentially truncatable pages at the end: %', free_pages_at_end;
    	RAISE NOTICE 'Amount of free space at the end of the table: %', free_space_at_end;
    ELSE
    	RAISE NOTICE 'There are no empty pages to truncate';
    END IF;
    RAISE NOTICE '-------------------------------------------------------------';
END;
$$ LANGUAGE plpgsql;

This handy script could be periodically executed to check the High Water Mark (HWM) and will produce the following output:

(postgres@10.3.1.17:5432) [postgres] > SELECT * FROM show_empty_pages('public.large_table');
NOTICE:  -------------------------------------------------------------
NOTICE:  Summary for table: public.large_table
NOTICE:  -------------------------------------------------------------
NOTICE:  The High Water Mark (HWM) is at page: 302534
NOTICE:  First potentially empty page is at: 302233
NOTICE:  Total Pages in Table: 302534
NOTICE:  Number of potentially truncatable pages at the end: 301
NOTICE:  Amount of free space at the end of the table: 2408 kB
NOTICE:  -------------------------------------------------------------

If there is no freespace after the last full block the output will look like this:

NOTICE:  -------------------------------------------------------------
NOTICE:  Summary for table: public.large_table
NOTICE:  -------------------------------------------------------------
NOTICE:  The High Water Mark (HWM) is at page: 302233
NOTICE:  There are no empty pages to truncate
NOTICE:  -------------------------------------------------------------

So while there is no right answer on how to deal with this, ensure you know the implications of each step in the process. In this case, we have decided to turn the “vacuum_truncation” option to false, but maybe another option might be to tune vacuum in another way such as either making it more or less frequent. Always evaluate your own situation, but in any case it’s always good to know what happens in your database when certain commands are executed.

Enjoy!

[syndicated profile] dxdt_feed

Posted by Александр Венедюхин

Очень много популярных статей “про квантовую механику” начинаются с дежурной фразы, утверждающей что-то вроде такого: “в квантовой механике – частица находится во многих точках пространства одновременно”. (Есть ещё полностью аналогичный вариант про пребывание во многих состояниях.) Примеры найти нетрудно, свежий есть на сайте Quanta Magazine.

Вообще, это сильно напоминает едва ли не столь же распространённую историю про “пересекающиеся параллельные прямые”: казалось бы, прямые – параллельные, но нет – “пересекаются”, да и всё тут!

Если частица “одновременно находится в нескольких местах”, то что это могло бы означать? Допустим, есть утверждение, что результат попытки измерения координат квантовой частицы может выдать разные значения с разной вероятностью. С одной стороны, все подобные экспериментальные измерения обладают некоторой погрешностью. Поэтому всегда можно ввести распределение верояностей.

С другой стороны, из того, что математическая модель позволяет построить распределение вероятностей, хорошо согласующееся с результатами последовательных измерений в сходных условиях, вовсе не следует обратное, не следует вывод, что и частица находится одновременно во всех этих точках пространства, которых, вообще говоря, можно насчитать сколько угодно – то есть, буквально, больше любого заданного натурального числа. При этом вовсе не запрещены эксперименты с локализацией квантовых частиц: соответствующая теория лишь позволяет с высокой точностью предсказывать распределение результатов для разных измерений, а не “размазывать” одну и ту же частицу – всякая работающая теория тут вообще про измерения, а не про частицы.

Естественно, можно считать, что это такое свойство – “размытие” частицы по “пространству”. Но если частица стала “размытым облаком”, то вот это размытое облако – и есть же область пространства, занимаемого частицей. То есть, если задуматься, то даже в такой интерпретации, – очень странной, – частица оказывается ещё более локализованной: вот же, описано, где она, буквально. Ну, хорошо, допустим, “сразу везде”, как и утверждается – экстремальный случай. Но отдельные точки пространства, необходимые для того, чтобы вообще “склеивать объёмы” и что-то сравнивать – как их определить? Точки всё равно оказываются некими наборами координат. И если за координаты принять вещественные числа, то утверждение, обратное к размытию вероятностей результатов измерения, опять перестаёт работать: практически невозможно попасть ни в какую заранее выбранную точку.

То есть, буквально, называете координаты точки, – например, (√2, π), – и всё – результат измерений “на приборах” всегда будет другим (потому что нельзя записать в десятичных дробях ни одну координату, ни вторую). А значит, частицу не удалось локализовать в достаточной мере, она осталась столь же “размытым облаком” – и где тогда проводить границу, по какому объёму? Если же сделать координаты дискретными, то необходимость “копирования частицы” по всем экспериментально мыслимым “кубикам” тут же исчезает вовсе, поскольку не только само вычисление вероятности не требует занятия всех возможных “кубиков” копиями частицы, но это не нужно и для непосредственного дискретного измерения.

Кстати, вот тут-то, конечно, сразу возникает и работает контраргумент Бернштейна к невозможности создания квантовых компьютеров, который про битовые строки: буквально – для вычислений над 1000-битными числами не обязательно все их хранить в памяти компьютера. Поэтому для вычисления значений функции, задающей вероятность результатов измерений координат в последовательных экспериментах, не нужно, чтобы частица была сразу во всех точках вычисляемого пространства. Зато вот если бы было нужно, то это тоже оказалось бы полезным. Вот только вряд ли об этом можно было бы узнать, поскольку такой расклад запретил бы не только обычные, но и квантовые компьютеры.

Посудите сами – все точки пространства забиты всеми возможными частицами за все возможные периоды времени и за все возможные эксперименты. Что это за пространство такое? Откуда оно берётся? Да, можно вспомнить про исходный огромный топос, сечение которого и есть наблюдаемый расклад окружающей действительности, но тогда в топос входит и, не менее обобщённое, пространство. Так что это не спасает утверждение про квантовую частицу, “пребывающую сразу во многих точках пространства”. Да и суждений таких в научпоп-статьях упомянутого типа “про кванты” что-то не встречается.

Это, впрочем, не отменяет более общего рассуждения про потоки “квантовых” вероятностей, нужные для работы того же алгоритма Шора: эти вероятности, предположим, таки должны быть где-то распределены до того, как проводится измерение, в отличие от обработки тысячи битов на классическом компьютере. Но никакой необходимости одновременного пребывания потенциально локализуемой частицы во множестве точек пространства – нет и здесь.

[syndicated profile] arstech_it_feed

Posted by Benj Edwards

On Thursday, Anthropic unveiled specialized AI models designed for US national security customers. The company released "Claude Gov" models that were built in response to direct feedback from government clients to handle operations such as strategic planning, intelligence analysis, and operational support. The custom models reportedly already serve US national security agencies, with access restricted to those working in classified environments.

The Claude Gov models differ from Anthropic's consumer and enterprise offerings, also called Claude, in several ways. They reportedly handle classified material, "refuse less" when engaging with classified information, and are customized to handle intelligence and defense documents. The models also feature what Anthropic calls "enhanced proficiency" in languages and dialects critical to national security operations.

Anthropic says the new models underwent the same "safety testing" as all Claude models. The company has been pursuing government contracts as it seeks reliable revenue sources, partnering with Palantir and Amazon Web Services in November to sell AI tools to defense customers.

Read full article

Comments

[syndicated profile] register_security_feed

Posted by Jessica Lyons

OpenAI boots accounts linked to 10 malicious campaigns

Fake IT workers possibly linked to North Korea, Beijing-backed cyber operatives, and Russian malware slingers are among the baddies using ChatGPT for evil, according to OpenAI's latest threat report.…

[syndicated profile] arstech_it_feed

Posted by Dan Goodin

Millions of low-cost devices for media streaming, in-vehicle entertainment, and video projection are infected with malware that turns consumer networks into platforms for distributing malware, concealing nefarious communications, and performing other illicit activities, the FBI has warned.

The malware infecting these devices, known as BadBox, is based on Triada, a malware strain discovered in 2016 by Kaspersky Lab, which called it "one of the most advanced mobile Trojans" the security firm's analysts had ever encountered. It employed an impressive kit of tools, including rooting exploits that bypassed security protections built into Android and functions for modifying the Android OS's all-powerful Zygote process. Google eventually updated Android to block the methods Triada used to infect devices.

The threat remains

A year later, Triada returned, only this time, devices came pre-infected before they reached consumers’ hands. In 2019, Google confirmed that the supply-chain attack affected thousands of devices and that the company had once again taken measures to thwart it.

Read full article

Comments

[syndicated profile] bruce_schneier_feed

Posted by Bruce Schneier

On Thursday I testified before the House Committee on Oversight and Government Reform at a hearing titled “The Federal Government in the Age of Artificial Intelligence.”

The other speakers mostly talked about how cool AI was—and sometimes about how cool their own company was—but I was asked by the Democrats to specifically talk about DOGE and the risks of exfiltrating our data from government agencies and feeding it into AIs.

My written testimony is here. Video of the hearing is here.

DNS-over-TLS и Timeweb

Jun. 6th, 2025 05:41 pm
[syndicated profile] dxdt_feed

Posted by Александр Венедюхин

Провайдер Timeweb, как я заметил, включил поддержку DNS over TLS на двух (как минимум) из своих массовых авторитативных серверов имён (NS): ns2.timeweb.ru., ns4.timeweb.org. Это означает, что резолверы могут использовать TLS при подключении к этим серверам, что автоматом делает DNS over TLS (DoT) довольно распространённой в Рунете технологией, если считать по зонам, так как упомянутые NS использует больше двух с половиной сотен тысяч DNS-зон в .RU.

DoT полезно внедрять на авторитативных серверах. Это защищает трафик резолвера при рекурсивном опросе. Подробно про DoT я недавно писал на “Хабре”.

Скриншот отчёта сервиса проверки настроек DNS:
Screenshot

МИНУС ДВА ПЕРЕЕЗДА

Jun. 6th, 2025 07:30 pm
[syndicated profile] ryb40_feed
Долгожданное событие, которое порадует автомобилистов.
[syndicated profile] ryb40_feed
В новом строительном сезоне к ремонту дворов и дорог будет применяться комплексный подход.
[syndicated profile] ryb40_feed
Накануне в Рыбинске случилось два ДТП, участниками которых стали нетрезвые водители.
[syndicated profile] ryb40_feed
Сегодня Рыбинск стал местом встречи руководителей государственных учреждений культуры Ярославской области.
[syndicated profile] ryb40_feed
В дошкольных учреждениях Рыбинска проходит комиссионная проверка готовности к новому учебному году.

"ЛИДЕРЫ КОМАНДЫ 76"

Jun. 6th, 2025 07:17 pm
[syndicated profile] ryb40_feed
В пятницу в городском Дворце молодежи стартовал конкурс профессионального мастерства среди работников сферы молодежной политики Ярославской области.
[syndicated profile] ryb40_feed
В детском школьном лагере на базе 10-й рыбинской школы прошли комплексные занятия по безопасности.

"ОБЕРЕГАЙ" ПЛАНЕТУ

Jun. 6th, 2025 07:08 pm
[syndicated profile] ryb40_feed
Берега Волги вновь очистил детский десант.
[syndicated profile] grahamcluley_feed

Posted by Graham Cluley

Over Easter, retail giant Marks & Spencer (M&S) discovered that it had suffered a highly damaging ransomware attack that left some shop shelves empty, shut down online ordering, some staff unable to clock in and out, and caused some of its major suppliers to resort to pen and paper.

In a gloating abuse-filled email to M&S CEO Stuart Machin, the DragonForce hacker group claimed responsibility for the attack.

Read more in my article on the Hot for Security blog.
[syndicated profile] register_security_feed

Posted by Connor Jones

Destructive malware has been a hallmark of Putin's multi-modal war

A new strain of wiper malware targeting Ukrainian infrastructure is being linked to pro-Russian hackers, in the latest sign of Moscow's evolving cyber tactics.…

Profile

beldmit: (Default)
Dmitry Belyavskiy

May 2025

S M T W T F S
    123
45678910
11121314151617
181920212223 24
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 8th, 2025 02:10 pm
Powered by Dreamwidth Studios